【问题标题】:The class variable is undefined in class method类变量在类方法中未定义
【发布时间】:2015-11-26 18:06:50
【问题描述】:

看看下面的简单代码。服务器告诉我函数car_detail() 中的wheel_count 未定义的错误。那么,为什么会这样呢?

你能帮帮我吗?

<?php 

class cars {

    var $wheel_count = 4;
    var $door_count = 4;

    function car_detail() {
        return $this->$wheel_count;
    }

}

$bmw = new cars();
echo $bmw->car_detail();

?>    

【问题讨论】:

    标签: php class methods


    【解决方案1】:

    使用$this-&gt;wheel_count 访问该属性:)

    请注意,您有一个额外的“$”。

    如果您有声明为static 的属性,那么您可以使用“$”访问它们:

    static $something = 'blah';
    
    function getSomething()
    {
        return self::$something;
    }
    

    ...或“在课堂之外”:

    $something = MyClass::$something;
    

    此外,请考虑使用更高级的代码编辑器/IDE,它会在您输入无效代码后立即通知您。

    【讨论】:

    • 非常感谢。实际上我有 phstorm 和 zen studio,但我不喜欢它们,因为我更喜欢 sublime text。再次感谢您!
    猜你喜欢
    • 2015-06-09
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多