【问题标题】:Call Child Method in Main Class在主类中调用子方法
【发布时间】:2015-11-17 10:48:33
【问题描述】:

我想在没有声明 new child() 的情况下调用主类中的子方法;

class main {
    function __construct() {

    }
    public function test() {

    }
 }

class child extends main {
    function __construct() {

    }
    function childmethod() {
        return "test";
    }
}

$main = new main();
$main->childmethod();

祝你好运

【问题讨论】:

标签: php


【解决方案1】:

将类设为abstract,并将要从子类调用的方法声明为abstract

abstract class main {
    function __construct() {

    }
    public function test() {
          return "test";
    }

  abstract function childmethod();
 }

class child extends main {
    function __construct() {

    }
    function childmethod() {
        return "childmethod";
    }
}

$main = new child();
echo $main->childmethod();// echoes childmethod
echo $main->test();// echoes test

【讨论】:

  • 它的extends,而不是@Uchiha 所说的extend Parse error: ...
  • 我刚刚复制了 OP 的问题。谢谢:)
  • 这行不通。您需要实例化 new child() 而不是 new main()
【解决方案2】:

如果我正确理解您的要求,您将无法做到,这是项目理念中的错误。 如果您需要在父级中调用子方法,则意味着该方法应该进入父级。

没有实例化对象就无法调用对象的方法,除非你创建一个静态方法

【讨论】:

  • 我创建了一个 json api。现在我想把它分成每个模式/区域的和平。例如:API - Refs - News - 这就是我有这个问题的原因。
  • 我明白了。但是当你发现父级中需要一个方法时,最好的方法是移动父级中的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 2013-04-27
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多