简体   繁体   中英

PHP Classes - Fatal error: Call to undefined method

test.php

class AClass {
    public function __construct()
    {
        echo '<strong style="color:blue;">AClass construct</strong><br>';
    }

    public function call()
    {
        $this->koko();
    }

    private function koko()
    {
        echo 'koko <br>';
    }
}

class BClass extends AClass {

    public function __construct()
    {
        echo '<strong style="color:red;">BClass construct</strong><br>';
        parent::__construct();
    }

    public function momo()
    {
        echo 'momo <br>';
    }
}


$xxx = new AClass(); // Output: AClass contruct ..... (where is BClass echo ?)
$xxx->call(); // Output: koko
$xxx->momo(); // Output: Fatal error: Call to undefined method AClass:momo()

Maybe newbe question but.... What is wrong ?

You got the wrong direction.. if ClassB extends ClassA, ClassB inherits everything from ClassA and not the other way.. So you have to write the Code as follows:

$xxx = new BClass();
$xxx->call();
$xxx->momo();
$xxx = new BClass();
$xxx->call();
$xxx->momo();

this can call

$aClass = new AClass();
$aClass->call();
// you can't call private method.

if you're not creating the object of class B then you can't call momo()

when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

Note: Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

<?php

class foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }

    public function printPHP()
    {
        echo 'PHP is great.' . PHP_EOL;
    }
}

class bar extends foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great' 
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>

Reference

您尝试访问的方法(momo)属于子类(BClass),而不属于基类(AClass),因此是错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM