简体   繁体   English

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

[英]Call function in function from another class PHP

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). 我想要做的是在function1 (在classA中) 中调用function2 (在classB中)。

How should I do this? 我该怎么做?

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM