无法访问空属性?

 收藏

我试图进入php面向对象的编程。

<?php
class myClass{

public $myVar="this is demo";

public function myTextdemo(){
        echo $myVar;
    }
}
$obj= new myClass;
echo $obj->$myVar;

?>

它说

致命错误:无法访问第11行的空属性

我的代码有什么问题?

回复
  • 回到最初 回复

    像这样更改它:

    <?php
    class myClass
    {
        public $myVar="this is demo";
    
        public function myTextdemo()
        {
            return $this->myVar; # the problem was here
        }
    }
    
    $obj = new myClass();
    echo $obj->myVar; # and here you wrote $obj->$myVar with an extra $
    ?>
    

    use return to output data from a function not echo and use $this inside the class functions, otherwise the declared property will not be considered and you will get an error like Undefined variable...

    http://www.php.net/manual/en/language.oop5.properties.php

    再见! :)

  • sunde 回复

    太棒了解决了。谢谢谷物:)