[英]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'. 如果我直接调用该类,则__constructor调用内部方法getPad并返回错误的答案“ 1”。 Instead, if I call the method getPad return the correct value '0001'. 相反,如果我调用方法getPad,则返回正确的值'0001'。
Why can't I use $cod_cliente=$cod->i=1
? 为什么我不能使用$cod_cliente=$cod->i=1
?
$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. 它将$cod_cliente
和$cod_cliente
$cod->i
都设置为1。因此,当您打印$cod_cliente
,它将显示1。
But in case $cod_cliente = $cod->getPad(1)
, code to add padding executes and return 0001
. 但是在$cod_cliente = $cod->getPad(1)
,执行添加填充的代码并返回0001
。
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. 并且由于您的getPad($i)
返回某些内容,因此您需要回显/打印结果。
<?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
. 这将回显0003
。
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. 非常感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.