如何从父类调用子类的函数?考虑一下:
class whale
{
function __construct()
{
// some code here
}
function myfunc()
{
// how do i call the "test" function of fish class here??
}
}
class fish extends whale
{
function __construct()
{
parent::construct();
}
function test()
{
echo "So you managed to call me !!";
}
}
Run Code Online (Sandbox Code Playgroud)
Flo*_*anH 98
这就是抽象类的用途.一个抽象类基本上说:无论谁继承我,都必须具备这个功能(或这些功能).
abstract class whale
{
function __construct()
{
// some code here
}
function myfunc()
{
$this->test();
}
abstract function test();
}
class fish extends whale
{
function __construct()
{
parent::__construct();
}
function test()
{
echo "So you managed to call me !!";
}
}
$fish = new fish();
$fish->test();
$fish->myfunc();
Run Code Online (Sandbox Code Playgroud)
Chr*_*gel 27
好的,这个答案很晚,但为什么没有人想到这个呢?
Class A{
function call_child_method(){
if(method_exists($this, 'child_method')){
$this->child_method();
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且该方法在扩展类中定义:
Class B extends A{
function child_method(){
echo 'I am the child method!';
}
}
Run Code Online (Sandbox Code Playgroud)
所以使用以下代码:
$test = new B();
$test->call_child_method();
Run Code Online (Sandbox Code Playgroud)
输出将是:
I am a child method!
Run Code Online (Sandbox Code Playgroud)
我用它来调用钩子方法,这些钩子方法可以由子类定义,但不一定要.
cle*_*tus 10
好吧,这个问题有很多问题,我真的不知道从哪里开始.
首先,鱼不是鲸鱼,鲸鱼不是鱼.鲸鱼是哺乳动物.
其次,如果你想从父类中不存在的父类调用子类中的函数,那么你的抽象是严重缺陷的,你应该从头开始重新考虑它.
第三,在PHP中你可以做到:
function myfunc() {
$this->test();
}
Run Code Online (Sandbox Code Playgroud)
在whale它的实例中将导致错误.在fish它的一个实例应该工作.
小智 6
从PHP 5.3开始,您可以使用static关键字从被调用的类中调用方法.即:
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
Run Code Online (Sandbox Code Playgroud)
上面的例子将输出:B
来源:PHP.net/Late Static Bindings