PHP 类 - 致命错误:调用未定义的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21231641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Classes - Fatal error: Call to undefined method
提问by AkisC
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 ?
也许是新的问题,但是.... 有什么问题?
回答by Philipp
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:
你走错方向了..如果 ClassB 扩展 ClassA,ClassB 继承 ClassA 的所有内容,而不是其他方式.. 所以你必须编写如下代码:
$xxx = new BClass();
$xxx->call();
$xxx->momo();
回答by Kaushik
$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 Bthen you can't call momo()
如果你没有创建类的对象,B那么你不能调用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'
?>
回答by raj
The method (momo) you are trying to access belongs to the child class (BClass) and not to the base class (AClass) and hence the error.
您尝试访问的方法 (momo) 属于子类 (BClass) 而不是基类 (AClass),因此是错误。

