class __constructor don't return zerofill number

45 Views Asked by At

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 ?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On
$cod_cliente = $cod->i = 1; 

It will set value for $cod_cliente and $cod->i both to 1. So when you print $cod_cliente, it will show 1.

But in case $cod_cliente = $cod->getPad(1), code to add padding executes and return 0001.

0
On

this is right code:

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

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

  }

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

now work:

$c= new codici(1);
echo $c->i;//return 0001
echo $c->getPad(1);//return 0001

thank a lot.