4

Within a single class, I am able to use the _call/_callStatic functions to call a function before any function is actually run. However, I'm yet to find a solution that I can apply to the parent, and it will be inherited by the children.

The only method I can think of is putting a small snippet of code within each class that calls a function in the parent, which contains my code.

Are there any better solutions that I can implement?

1
  • 1
    __call does get inherited by child-classes. And it doesn't get run 'before any function is actually run'. It is being called when the function you're actually calling doesn't exists (or is inaccessible in that scope). Your question isn't very clear to me. Can you add some demo-code? Commented Dec 9, 2013 at 21:56

3 Answers 3

1

As long as you are at least on php 5.4, you could use traits. http://php.net/traits

This will need some adjustments in your code but could allow the desired behavior. Do you have some more information on your use case? I think of logging from your description, is this correct?

3
  • Every time a function is run, I want to log the fact that it's been run, along with it's class, name and arguments.
    – Ryan
    Commented Dec 10, 2013 at 17:45
  • Throughout a whole application? This could also be possible via call stack. Otherwise it might be pretty difficult or at least it would break some "good coding" practice. I will think about it and maybe provide some example. Commented Dec 12, 2013 at 16:02
  • Yeah, throughout the entire application. I've got one main class which has some initialisation functions, and a few classes that extend that main class which each contain functions related to a different purpose.
    – Ryan
    Commented Dec 12, 2013 at 19:26
0

Unfortunately there are not magic methods in PHP which get run whenever any method is called.

I think the solution you are looking for is a decorator, see this article for the tips on decorating methods / classes in PHP.

how to implement a decorator in PHP?

0

It's hard to help you without seeing some code. However, assuming that you don't re-define __call/__callStatic in the subclass, it should simply inherit the method from it's superclass.

If you do re-define __call/__callStatic in the subclass, it overrides the superclass' definition. So you'd somehow have to call the superclass' method. In order to do this you can use the parent keyword. See this example:

class SuperClass
{
    public function __call($name, $arguments)
    {
        // Do some stuff
    }
}

class SubClass extends SuperClass
{
    public function __call($name, $arguments)
    {
        // Execute the parent's __call() method
        return parent::__call($name, $arguments);

        // Do some extra stuff here
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.