【问题标题】:PHP Fatal error: Call to a member function getScore() on a non-object inPHP致命错误:在非对象上调用成员函数getScore()
【发布时间】:2011-06-16 04:46:45
【问题描述】:

这是我的第一个问题

我有以下课程

class ProDetection {
public function ProDetection ( ) { }
public function detect($word) {
    ............
}
public function getScore() {
    return $score;
}
}

class SaveDetection {
public function SaveDetection($words) {
    $proDetection = new ProDetection();
    for($i=0;$i<sizeof($words);$i++) {
        $proDetection->detect($words[$i]);
    }
}
public function getScore() {
    return $this->proDetection->getScore();\\line 22
}
}

在其他 PHP 文件中,我尝试调用 SaveDetection 到 getScore();

$konten = "xxxx xxxx xxx";
$save = new SaveDetection($konten);
print_r( $save->getScore() );

但我收到一条错误消息

注意:未定义的属性:第 22 行 C:\xampp\htdocs\inovasi\SaveDetection.php 中的 SaveDetection::$proDetection

致命错误:在第 22 行对 C:\xampp\htdocs\inovasi\SaveDetection.php 中的非对象调用成员函数 getScore()

需要你的帮助

【问题讨论】:

    标签: php


    【解决方案1】:

    您从不声明$proDetection 成员变量。基本上在您的 SaveDetection 构造函数中,您将 $proDetection 声明为局部变量

    class SaveDetection {
    
        public function SaveDetection($words) {
            $this->proDetection = new ProDetection();
            for($i=0;$i<sizeof($words);$i++) {
                $this->proDetection->detect($words[$i]);
            }
        }
        public function getScore() {
            return $this->proDetection->getScore();\\line 22
        }
    
        private $proDetection;
    
    }
    

    编辑:

    PS。您应该真正使用 PHP 的 __construct() 语法而不是旧式的构造函数。见here

    class SaveDetection {
    
        public function __construct($words) {
            $this->proDetection = new ProDetection();
            for($i=0;$i<sizeof($words);$i++) {
                $this->proDetection->detect($words[$i]);
            }
        }
    

    【讨论】:

    • 嗨 gww' 非常感谢,它的工作!
    • 太棒了。感谢快速重播
    【解决方案2】:

    试试这个。将您的变量声明为私有(因为如果您的代码增长,很难找到类中使用的所有对象或变量。)

    class SaveDetection {
        private $proDetection = null;
        public function __construct($words) {
            $this->proDetection = new ProDetection();
            for($i=0;$i<sizeof($words);$i++) {
                $this->proDetection->detect($words[$i]);
            }
        }
        public function getScore() {
            return $this->proDetection->getScore();\\line 22
        }
    
        private $proDetection;
    
    }
    

    【讨论】:

    • 嗨,Sahal,非常感谢。这是工作
    猜你喜欢
    • 2016-02-12
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多