PHP类 - 致命错误:调用未定义的方法

问题描述:

test.php的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() 

也许newbe的问题,但....有什么不对?

+1

您还没有宣布BClass,'$ xxx'是ACLASS的一个实例。因此,该方法不存在。 – MackieeE

+1

当您尝试调用的函数位于继承的类Bclass中时,您正在调用基类。尝试$ xxx = new Bclass() –

+0

如果你要使用继承,那么一定要[学习如何工作](http://www.php.net/manual/en/language.oop5.inheritance.php)。 –

你得到了错误的方向。如果ClassB的延伸ClassA的,ClassB的继承ClassA的一切,而不是其他方式。所以,你必须编写的代码如下:

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

不幸的是父方法没有被调用,出于某种原因PHP类必须有自己的方法,即使它扩展的方法有方法 - php 5.5.9 – NoBugs

+1

@NoBugs如果你想在一个重载方法中调用父方法,你必须明确地用'parent :: methodName(...)'来执行此操作。# – Philipp

+0

@Philipp指导我如何解决错误 - 致命错误:调用未定义的方法Mage_Catalog_Model_Resource_Product_Flat :: loadAlltribute()in/home/abc第435行的/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php – Rathinam

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

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

this can call 

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

,如果你没有创建类B的对象,那么你不能调用momo()

当你扩展一个类时,子类继承父类的所有公共和受保护的方法。除非一个类重写这些方法,否则它们将保留它们的原始功能。

注意: 除非使用自动加载,否则类必须在它们被使用之前被定义。如果一个类扩展了另一个类,那么父类必须在子类结构之前声明。此规则适用于继承其他类和接口的类。

<?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