Class test{
function test1()
{
echo 'inside test1';
}
function test2()
{
echo 'test2';
}
function test3()
{
echo 'test3';
}
}
$obj = new test;
$obj->test2();//prints test2
$obj->test3();//prints test3
Now my question is,
How can i call another function before any called function execution? In above case, how can i auto call 'test1' function for every another function call, so that i can get the output as,
test1
test2
test1
test3
currently i am getting output as
test2
test3
I cannot call 'test1' function in every function definition as there may be many functions. I need a way to auto call a function before calling any function of a class.
Any alternative way would also be do.
Your best bet is the magic method __call, see below for example:
Please notice that
test2
andtest3
are not visible in the context where they are called due toprotected
andprivate
. If the methods are public the above example will fail.test1
does not have to be declaredprivate
.ideone.com example can be found here
Updated: Add link to ideone, add example with return value.