简体   繁体   中英

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.

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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