4

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?

2
  • 3
    Needs more info - do you have an initialized instance of classB in classA? Commented Dec 7, 2011 at 18:23
  • If you aren't accessing any data members from that class, make the function static. Then you can call it using: MyClass::myFunction. Commented Dec 7, 2011 at 18:25

1 Answer 1

17

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(); 
Sign up to request clarification or add additional context in comments.

3 Comments

useful info. Thanks for the methods.
What if the class is in a different directory?
from PHP 5.4 you should use (new ClassName)->method();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.