gpt4 book ai didi

PHP : Best way to call an object method from another object ?

转载 作者:可可西里 更新时间:2023-11-01 00:02:53 24 4
gpt4 key购买 nike

我正在寻找从另一个类调用类方法的最佳方法,而不必使用 Global 来获取类实例,因为我现在明白“全局是邪恶的”!

下面是一些代码来解释它:

class Assets{
public $assets = array();
public function add($asset){
$this->assets[] = $asset;
}
}

现在我想在这里调用 Assets/call 方法 ..

$assets = new Assets;
class Form{
public function __construct(){
global $assets;
$assets->add('Form');
}
}

在这种情况下使用 Global 是不是很糟糕?如果是这样,还有什么其他方式被认为是最好的?

PS:我只需要使用该类的一个实例;意味着我不想在第二个类中创建一个新实例。

最佳答案

如果您只想拥有 1 个 Assets 实例,则需要使用某种形式的依赖注入(inject)。

在这种情况下最明显的是通过构造函数传递它:

class Form{
public function __construct(Assets $assets){
$assets->add('Form');
}
}

使用全局变量确实是个坏主意。

关于PHP : Best way to call an object method from another object ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16797283/

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