【问题标题】:class __constructor don't return zerofill number类 __constructor 不返回填零数
【发布时间】:2018-06-27 10:14:27
【问题描述】:

我有这门课:

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);
    }
}

我就是这样使用它的:

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

如果我直接调用类,__constructor 调用内部方法 getPad 并返回错误答案“1”。相反,如果我调用 getPad 方法,则返回正确的值“0001”。

为什么我不能使用$cod_cliente=$cod->i=1

【问题讨论】:

  • $cod_cliente=$cod->i=1 不符合您的预期。
  • 构造函数是初始化对象的神奇方法。当 __construct() 被调用时 $this->i 没有值所以你不能用它来设置另一个值
  • 好的,我猜对了。

标签: php class constructor zerofill


【解决方案1】:
$cod_cliente = $cod->i = 1; 

它将$cod_cliente$cod->i 的值都设置为1。因此,当您打印$cod_cliente 时,它将显示1。

但在$cod_cliente = $cod->getPad(1)的情况下,添加填充的代码会执行并返回0001

【讨论】:

    【解决方案2】:

    如果你想让你的构造函数返回一些东西,你应该给它一个参数。而且由于您的 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);
        }
    }
    

    这将允许你这样调用你的类:

    $c = new codici(3);
    

    这会回显0003

    【讨论】:

      【解决方案3】:

      这是正确的代码:

      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);
        }
       }
      

      现在工作:

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

      非常感谢。

      【讨论】:

        猜你喜欢
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        • 2016-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多