Search code examples
phpclassconstructorzerofill

class __constructor don't return zerofill number


I have this class :

class codici {
    public $i;
    public $len;
    public $str;
    public $type;

    function __construct()
    {
        $this->getPad($this->i);
    }

    public function getPad($i)
    {
        return ''.str_pad($i,4,'0',0);
    }
}

And I use it in this way :

$cod = new codici();
$cod_cliente = $cod->i = 1; //return 1
$cod_cliente = $cod->getPad(1); //return 0001

If I call the class direct, __constructor call internal method getPad and returns wrong answer '1'. Instead, if I call the method getPad return the correct value '0001'.

Why can't I use $cod_cliente=$cod->i=1 ?


Solution

  • If you want your constructor to return something you should give it a parameter. And since your getPad($i) returns something you'd need to echo/print the results.

    <?php
    
    class codici {
        public $i;
        public $len;
        public $str;
        public $type;
    
        function __construct($parameter)
        {
            $this->i = $parameter;
            echo $this->getPad($this->i);
    
        }
    
        public function getPad($i)
        {
            return ''.str_pad($i,4,'0',0);
        }
    }
    

    This will allow you to call your class like this:

    $c = new codici(3);
    

    which would echo 0003.