假设我有一个类
<?php
class MyClass extends OtherClass
{
public function foo()
{
// some stuff
}
public function bar()
{
// some stuff
}
public function baz()
{
// some stuff
}
}
现在我需要添加另一个方法,它需要从其他所有方法中调用。
private function run_this()
{
$mandatary = true;
return $mandatary;
}
我可以在每个方法中添加一个简单的$this->run_this()
,好吧,但是否可以添加一些"神奇"的接收者来从这个类的每个方法中调用run_this()
?
我仍然认为你在做一些事情,因为你在某个地方有设计问题(XY问题),但是如果你坚持按照你的要求做,你可以装饰这个类:
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();
这有点难说,上面的工作原理和你要求的一样,但正如前面所说,这很可能不是你真正想做的。
你能不使用构造函数吗?
<?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
}
}
好吧,这是一种变体。
不完全确定你想要什么,但如果你想让它对所有子对象都可用,我会把它作为一个受保护的函数放在其他类中。这样只有子对象才能访问它
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
}
}