Reputation: 25315
I'd like to know if a class is going to call a certain method, but I want to know before instantiating the class. Is this possible?
Example: class Controller_Index
calls $this->composite('SomeCompositeClass')
within its __construct()
method. Class SomeCompositeClass
has a helloWorld()
method. I want to see if I can call Controller_Index->helloWorld()
.
Basically I want to see if my controller is going to add any composite classes (by using $this->composite()
), so that I may check if those composite classes contain the method I'm requesting (helloWorld()
). And I'd like to do this without having to first instantiate Controller_Index
.
Thanks!
Edit
I suppose what I want to do is similar to using PHP's Reflection classes to see if a class method exists. But I don't want to know if the method exists, I want to know if the class calls it.
Edit 2
Interfaces won't help because I won't necessarily call $this->composite()
from every controller.
Perhaps I just need to rethink the problem and go with a different approach.
Upvotes: 1
Views: 263
Reputation: 49396
First of all, you cannot do this in general. Analysing general code to see if it will ever reach a certain point in its execution is undecidable, hence even if you syntactically detect calls to composite
, you don't know if they'll be executed without actually executing the code.
Now, in a practical sense, you might be able to get some leverage by loading the code as text, and examining it for calls to composite
, but this will only be any use at all if you write the classes in a consistent fashion. It won't show calls hiding behind chains of function calls, will falsely flag conditionally guarded calls, and so forth. You're almost certainly better off using another method, such as PHP interfaces for static analysis like this.
Upvotes: 3
Reputation: 162849
I don't think you can programatically predict what a class's constructor is going to call when it executes without actually executing the code, unless you want to get into the realm of interpreting the actual language without executing it. IMO, this approach is a very roundabout way of ensuring that a class implements a specific method. Why not use interfaces? You may also be able to refactor your composite() method to use type hinting to ensure that only your interface type (containing your hellowworld() method) is used by the composite() method.
Upvotes: 1
Reputation: 25687
If you want to have a class function that is called without initiating any object of it just, You are looking for "static method".
Basically static methods belong to class NOT the class object. So you can called it without initializing it first like 'Class1::doStaticMethodAction()'
.
Upvotes: 0