PHP致命错误:对中的非对象调用成员函数getScore()

PHP致命错误:对中的非对象调用成员函数getScore(),php,Php,这是我的第一个问题 我有以下课程 class ProDetection { public function ProDetection ( ) { } public function detect($word) { ............ } public function getScore() { return $score; } } class SaveDetection { public function SaveDetection($words) { $proD

这是我的第一个问题

我有以下课程

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
}
}
但我收到了一条错误信息

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

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


请需要您的帮助

您从未声明
$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;

}

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

类存储检测{
private$proDetection=null;
公共功能结构($words){
$this->proDetection=newprodetection();
对于($i=0;$iproDetection->detect($words[$i]);
}
}
公共函数getScore(){
返回$this->proDetection->getScore();\\line 22
}
私人生产检测;
}

Hi gww'非常感谢,它的工作!太棒了。感谢快速重播Hi Sahal,非常感谢。它的工作
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;

}
class SaveDetection {

    public function __construct($words) {
        $this->proDetection = new ProDetection();
        for($i=0;$i<sizeof($words);$i++) {
            $this->proDetection->detect($words[$i]);
        }
    }
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;

}