代码之家  ›  专栏  ›  技术社区  ›  Josh K

PHP类变量问题

  •  0
  • Josh K  · 技术社区  · 15 年前

    我有这门课:

    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中的空属性

    发生什么事?

    3 回复  |  直到 15 年前
        1
  •  3
  •   Kevin Peno    15 年前

    移除调用中的$before testvar:

    $this->testvar = "Hullo";
    echo($this->testvar); 
    
        2
  •  6
  •   jheddings    15 年前

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

    $this->testvar;
    

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

    $testvar = 'myvar';
    $this->$testvar == $this->myvar;
    
        3
  •  2
  •   Alex    15 年前

    自从 var 我建议将其声明为私有、公共或受保护。

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