开发者

PHP Fatal error: Call to a member function getScore() on a non-object in

this is my first question

I Have following class

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<开发者_JS百科sizeof($words);$i++) {
        $proDetection->detect($words[$i]);
    }
}
public function getScore() {
    return $this->proDetection->getScore();\\line 22
}
}

in other PHP file, i'm try to calling SaveDetection to getScore();

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

But i got an error message

Notice: Undefined property: SaveDetection::$proDetection in C:\xampp\htdocs\inovasi\SaveDetection.php on line 22

Fatal error: Call to a member function getScore() on a non-object in C:\xampp\htdocs\inovasi\SaveDetection.php on line 22

Please need your help


You never declare the the $proDetection member variable. Basically in your SaveDetection constructor you are declaring $proDetection as a local variable

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;

}

EDIT:

PS. You should really use PHP's __construct() syntax instead of the old style of constructors. See here.

class SaveDetection {

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


Try this. Declare your variables as private (Coz if your code grows, it is hard to find what all the object or variables are used in the class.)

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;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜