【问题标题】:Can't assign value using $this in class无法在类中使用 $this 赋值
【发布时间】:2016-07-21 13:24:18
【问题描述】:

我有这样的课

Class something{
    public $token;

    public function nameA()
    {
        $this->token = 'value';
    }
    public function nameB(){
        echo $this->token;
    }
}

$ok = new something();
$ok->nameB();

为什么我在使用 $ok->nameB(); 时什么也得不到?

【问题讨论】:

  • 因为new something(); 不会自动为您运行nameA();除非您调用 nameA(),否则 token 属性的值为空

标签: php class


【解决方案1】:

如果您要在类中使用自然构造函数方法,那么您的代码就可以了

Class something{
    public $token;

    public function __construct()
    {
        $this->token = 'value';
    }
    public function nameB(){
        echo $this->token;
    }
}

$ok = new something();
$ok->nameB();

【讨论】:

  • 它可以工作,但是除了使用 __construnt() 之外,我还有其他方法可以插入值吗?
  • 使用您的代码,您需要先调用nameA()
  • 从技术上讲,他们已经将token 设置为公共类成员——您可以通过$ok->token = "fred"; echo $ok->token; //prints "fred" 对其进行操作,该类没有以任何方式封装。
【解决方案2】:

你必须在赋值之前调用nameA(),这里的token是空的。

【讨论】:

    【解决方案3】:

    属性$token 在给定值之前为空。

    在您的课程中,发生这种情况的唯一方法是调用 nameA 方法,或者您直接操作属性,因此您需要先执行此操作:

    Class something{
        public $token;
    
        public function nameA()
        {
            $this->token = 'value';
        }
        public function nameB(){
            echo $this->token;
        }
    }
    
    $ok = new something();
    $ok->nameA(); //<--sets property
    //or direct manipulation: $ok->token = 'blah';
    $ok->nameB(); //<-- reads and outputs it
    

    另一种方法是在构造函数中设置属性:

    Class something{
        public $token;
    
        public function __construct()
        {
            $this->token = 'value';
        }
        public function nameB(){
            echo $this->token;
        }
    }
    
    $ok = new something(); //<-- sets propery
    $ok->nameB(); //<--reads and outputs it
    

    或者你可以用一个值初始化属性:

    Class something{
        public $token = 'default';
    
        public function nameA()
        {
            $this->token = 'value';
        }
        public function nameB(){
            echo $this->token;
        }
    }
    
    $ok = new something();
    $ok->nameB(); //outputs 'default'
    $ok->nameA(); //sets to 'value'
    $ok->nameB(); //outputs 'value'
    

    【讨论】:

    • 不错的答案 - 与 SO“最快的手指优先”效果相悖...
    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 2011-05-01
    • 2011-03-15
    • 2019-01-05
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多