【问题标题】:PHP Class Variable problemPHP类变量问题
【发布时间】:2010-12-12 10:19:56
【问题描述】:

我有这门课:

class TestClass
{
    var $testvar;
    public function __construct()
    {
        $this->$testvar = "Hullo";
        echo($this->$testvar);
    }
}

还有这个访问方法:

function getCurrent()
{
    $gen = new TestClass();
}

我收到以下错误:

注意:未定义变量:第 28 行 /Users/myuser/Sites/codebase/functions.php 中的 testvar
致命错误:无法访问第 28 行 /Users/myuser/Sites/codebase/functions.php 中的空属性

发生了什么事?

【问题讨论】:

    标签: php html class


    【解决方案1】:

    访问变量时不需要使用变量引用:

    $this->testvar;
    

    通过使用$this->$testvar,您的PHP 脚本将首先查找$testvar,然后在您的类中查找该名称的变量。即

    $testvar = 'myvar';
    $this->$testvar == $this->myvar;
    

    【讨论】:

      【解决方案2】:

      在您调用它时删除 testvar 之前的 $:

      $this->testvar = "Hullo";
      echo($this->testvar); 
      

      【讨论】:

        【解决方案3】:

        由于 var 已被弃用,我建议将其声明为私有、公共或受保护之一。

        class TestClass
        {
            protected $testvar;
            public function __construct()
            {
                $this->testvar = "Hullo";
                echo $this->testvar;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          相关资源
          最近更新 更多