首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP:如何从父类调用子类的函数

PHP:如何从父类调用子类的函数
EN

Stack Overflow用户
提问于 2009-12-22 16:03:30
回答 8查看 97.1K关注 0票数 70

如何从父类调用子类的函数?请考虑以下内容:

代码语言:javascript
复制
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 !!";
  }

}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2009-12-22 16:28:24

这就是abstract classes的作用。一个抽象类基本上是说:无论谁从我这里继承,都必须有这个函数(或这些函数)。

代码语言:javascript
复制
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();
票数 119
EN

Stack Overflow用户

发布于 2013-01-05 05:37:16

从PHP5.3开始,您可以使用static关键字来调用被调用类中的方法。即:

代码语言:javascript
复制
<?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

来源:PHP.net / Late Static Bindings

票数 13
EN

Stack Overflow用户

发布于 2009-12-22 16:10:21

好的,这个问题有太多的错误,我真的不知道从哪里开始。

首先,鱼不是鲸,鲸也不是鱼。鲸鱼是哺乳动物。

其次,如果您想从父类中不存在的父类调用子类中的函数,那么您的抽象是有严重缺陷的,您应该从头开始重新考虑。

第三,在PHP中你可以这样做:

代码语言:javascript
复制
function myfunc() {
  $this->test();
}

whale的一个实例中,它将导致错误。在fish的一个实例中,它应该可以工作。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1944827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档