【问题标题】:PHP Class; Notice: Undefined property errorPHP类;注意:未定义的属性错误
【发布时间】:2014-01-13 04:18:37
【问题描述】:

在我问我的问题之前,我想说我搜索了这个问题,其他答案都没有帮助......

基本上,在我的班级DemoClass中,我有4个函数,它们都是“未定义的属性”

我的错误:

注意:未定义的属性:第 46 行 /home/content/92/10270192/html/class.php 中的 DemoClass::$function

注意:第 46 行是我做 $demoClass->function...

我有一个典型的班级设置:

class DemoClass {
    public function __construct () {
        // stuff that works and gets called
    }
    public function testFunct () {
        // one that is an "undefined property"
    }
}

我照常上课:

$testClass = new DemoClass();
var_dump(testClass->testFunct); // this is what is on line 46
// ^^^ This also gives me NULL, because its undefined (? i guess...)

我从来没有遇到过这个问题,有什么建议吗?谢谢!

【问题讨论】:

    标签: php function class undefined


    【解决方案1】:

    调用函数时需要括号。改为$testClass->testFunct()

    【讨论】:

    • 我很抱歉 - 这是问题中的一个错字,我在我的实施中是正确的......
    • 应该是$testClass(美元符号前缀)
    【解决方案2】:

    $testClass->testFunct 引用类中的变量testFunct。您需要使用$testClass->testFunct() 来引用类中的函数。

    【讨论】:

    • 我有那么笨吗?等等......是的,我是 - 谢谢!我需要睡一会儿;)
    • 在你破坏任何代码之前上床睡觉,然后恢复精神! :-)
    【解决方案3】:

    应该是

    var_dump(testClass->testFunct())
    

    函数总是需要括号,因为否则(如您所见)您无法区分函数和常量之间的区别。

    【讨论】:

      【解决方案4】:

      与 JavaScript 不同,PHP 不将类方法作为常规属性处理。

      当您使用$testClass->testFunct 时,PHP 会查找名为testFunct属性,但没有找到。

      可以通过类名引用方法,在您的情况下为DemoClass::testFunct

      【讨论】:

      • 注意:通过类名访问方法,如DemoClass::testFunct,要求方法为static
      • 从技术上讲,您可以访问它,但尝试调用它最终会流泪(这使得这种访问确实非常有限)。
      猜你喜欢
      • 2012-10-01
      • 2016-11-12
      • 2011-03-05
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 2016-10-03
      • 2011-05-26
      相关资源
      最近更新 更多