Execute (magic) method when calling an existing method

Is there a magic method when, when a certain method is called from an object, the magic method is first called. Kinda as the __call method, but this only works when the method is not found.

So, in my case, I would like something like this:

class MyClass
{
    public function __startMethod ( $method, $args )
    {
        // a method just got called, so  this is called first
        echo ' [start] ';
    }

    public function helloWorld ( )
    {
        echo ' [Hello] ';
    }
}

$obj = new MyClass();
$obj->helloWorld();

//Output:
[start] [Hello] 

Is there something similar in PHP?

+5
source share
3 answers

There is no direct way to do this, but it seems to me that you are trying to implement a form of aspect-oriented programming. There are several ways to achieve this in PHP, you would need to configure your class as follows:

class MyClass
{
    public function __startMethod ( $method, $args )
    {
        // a method just got called, so  this is called first
        echo ' [start] ';
    }

    public function _helloWorld ( )
    {
        echo ' [Hello] ';
    }

    public function __call($method, $args)
    {
        _startMethod($method, $args);
        $actualMethod = '_'.$method;
        call_user_func_array(array($this, $actualMethod), $args);
    }
}

$obj = new MyClass();
$obj->helloWorld();

Check out other ways to implement AOP in PHP to see what works best for you (I'll see if I can find the link somewhere).

EDIT: http://www.liacs.nl/assets/Bachelorscripties/07-MFAPouw.pdf

+3

.

, , (: hidden_helloWorld), __call hidden_, . , , ..

+2

You can achieve this by making your methods private and calling methods using the __call () method. How:

<?php

class MyClass{
    function __call($methd, $args){
        if(method_exists($this, $mthd)){
            $this->$mthd($args);
        }
    }

    private function mthdRequired($args){
        //do something or return something
    }

The mthdRequired method is not called, except for a call. Hope this is helpful.

+1
source

All Articles