gpt4 book ai didi

PHP(面向对象): how call a new method in every methods

转载 作者:行者123 更新时间:2023-12-02 05:17:29 25 4
gpt4 key购买 nike

假设我有一个类

<?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 problem),但是如果你坚持按照你的要求去做,你可以装饰类:

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(面向对象): how call a new method in every methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28559015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com