Let's say I have a Class
<?php
class MyClass extends OtherClass
{
public function foo()
{
// some stuff
}
public function bar()
{
// some stuff
}
public function baz()
{
// some stuff
}
}
Now I need to add another method, that need to be called from every other method.
private function run_this()
{
$mandatary = true;
return $mandatary;
}
I can add a simple $this->run_this()
in every method, OK, but is it possible to add some "magic" recipient to invoke run_this()
from every method of this class?
Not entirely sure what you want, but if you want it availabe to all child objects I would put it in other class as a protected function. That way only child objects have access to it.
class OtherClass {
protected function run_this()
{
$mandatary = true;
return $mandatary;
}
}
class MyClass extends OtherClass
{
public function foo()
{
$mandatory = $this->run_this();
// some stuff
}
public function bar()
{
$mandatory = $this->run_this();
// some stuff
}
public function baz()
{
$mandatory = $this->run_this();
// some stuff
}
}
Could you not use the constructor ?
<?php
class MyClass extends OtherClass
{
function __construct() {
$mandatory = $this->run_this();
}
private function run_this()
{
$mandatary = true;
return $mandatary;
}
public function foo()
{
// some stuff
if ($this->mandatory) {
//true
} else {
//false
}
}
public function bar()
{
// some stuff
}
public function baz()
{
// some stuff
}
}
well some variation of that.
I still reeeeally think you are doing something because you have a design issue somewhere (XY problem), however if you insist in doing what you asked you could decorated the class:
class OtherClass {}
class MyClass extends OtherClass
{
public function foo()
{
// some stuff
}
public function bar()
{
// some stuff
}
public function baz()
{
// some stuff
}
public function run_this()
{
$mandatary = true;
return $mandatary;
}
}
class MyClassDecorator
{
private $myClass;
public function __construct($myClass)
{
$this->myClass = $myClass;
}
public function __call($name, array $arguments)
{
// run the mthod on every call
$this->myClass->run_this();
// run the actual method we called
call_user_func_array ([$this->myClass, $name], $arguments)
}
}
$myClass = new MyClass();
$decorator = new MyClassDecorator($myClass);
// will first run the `run_this` method and afterwards foo
$decorator->foo();
// etc
//$decorator->bar();
It's a bit hard to tell and the above works like you asked, however as stated before this is most likely not what you actually want to do.