如何从父类调用子类的函数?请考虑以下内容:
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 !!";
}
}
发布于 2009-12-22 16:28:24
这就是abstract classes的作用。一个抽象类基本上是说:无论谁从我这里继承,都必须有这个函数(或这些函数)。
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();
发布于 2013-01-05 05:37:16
从PHP5.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();
?>
上面的示例将输出:b
发布于 2009-12-22 16:10:21
好的,这个问题有太多的错误,我真的不知道从哪里开始。
首先,鱼不是鲸,鲸也不是鱼。鲸鱼是哺乳动物。
其次,如果您想从父类中不存在的父类调用子类中的函数,那么您的抽象是有严重缺陷的,您应该从头开始重新考虑。
第三,在PHP中你可以这样做:
function myfunc() {
$this->test();
}
在whale
的一个实例中,它将导致错误。在fish
的一个实例中,它应该可以工作。
https://stackoverflow.com/questions/1944827
复制相似问题