从另一个类 PHP 调用函数中的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8420431/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:40:03  来源:igfitidea点击:

Call function in function from another class PHP

phpclassfunctionabstract

提问by Fredrik

I have read a few threads about abstract class here at Stackoverflow and I think it's what I need, but I can't get the declaration straight.

我在 Stackoverflow 上阅读了一些关于抽象类的线程,我认为这正是我所需要的,但我无法直接得到声明。

What I want to do is to call a function2(in classB) in a function1(in classA).

我想要做的是在函数1(在类A中)调用函数2(在类B中)。

How should I do this?

我该怎么做?

回答by rdlowrey

If you only need to access ClassB's method from ClassA but don't need a parent-child relationship between the two, a static method may be more appropriate:

如果只需要从 ClassA 访问 ClassB 的方法,而不需要两者之间的父子关系,那么静态方法可能更合适:

class ClassA
{
  public function method1() {
    echo ClassB::method2();
  }
}

class ClassB
{
  public static function method2() {
    return 'WOOT!';
  }
}

$cls_a = new ClassA();
$cls_a->method1();

// or alternatively, you don't even need to instantiate ClassA
echo ClassB::method2();