gpt4 book ai didi

PHP:提供静态和非静态方法的类的设计模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:13 26 4
gpt4 key购买 nike

我的目标是创建可以同时使用staticnon-static 方式的类。两种方式都必须使用相同的方法,但方式不同

非静态方式:

$color = new Color("#fff");
$darkenColor = $color->darken(0.1);

静态方式:

$darkenColor = Color::darken("#fff", 0.1);

因此在此示例中,darken 方法既可用于现有对象,也可用作 Color 类的静态方法。但是根据它的使用方式,它使用不同的参数。

应该如何设计这样的类?创建此类类的好的模式是什么?

类会有很多不同的方法,因此应该避免在每个方法的开头进行大量检查代码。

最佳答案

PHP 并不真正支持方法重载,因此实现起来并不那么简单,但还是有办法的。

为什么要提供静态和非静态?

不过,我首先要问自己的是,是否真的需要同时提供静态和非静态方法。它看起来过于复杂,可能会让你的颜色类别的用户感到困惑,而且似乎并没有增加那么多好处。我只想使用非静态方法并完成它。

静态工厂类

你基本上想要的是静态工厂方法,所以你可以创建一个额外的类来实现这一点:

class Color {

private $color;

public function __construct($color)
{
$this->color = $color;
}

public function darken($by)
{
// $this->color = [darkened color];
return $this;
}
}

class ColorFactory {
public static function darken($color, $by)
{
$color = new Color($color);
return $color->darken($by);
}
}

另一种方法是将静态方法放在 Color 中并给它一个不同的名称,例如 createDarken(每次都应该相同,所以所有静态工厂为了方便用户,方法将被称为 createX

调用静态

另一种可能性是使用魔法方法__call__callStatic。代码应如下所示:

class Color {

private $color;

public function __construct($color)
{
$this->color = $color;
}

// note the private modifier, and the changed function name.
// If we want to use __call and __callStatic, we can not have a function of the name we are calling in the class.
private function darkenPrivate($by)
{
// $this->color = [darkened color];
return $this;
}

public function __call($name, $arguments)
{
$functionName = $name . 'Private';
// TODO check if $functionName exists, otherwise we will get a loop
return call_user_func_array(
array($this, $functionName),
$arguments
);
}

public static function __callStatic($name, $arguments)
{
$functionName = $name . 'Private';
$color = new Color($arguments[0]);
$arguments = array_shift($arguments);
// TODO check if $functionName exists, otherwise we will get a loop
call_user_func_array(
array($color, $functionName),
$arguments
);
return $color;

}
}

请注意,这有点困惑。就个人而言,我不会使用这种方法,因为它对您类(class)的用户来说不是那么好(您甚至不能拥有适当的 PHPDocs)。不过,对于作为程序员的您来说,这是最简单的,因为您在添加新功能时不需要添加很多额外的代码。

关于PHP:提供静态和非静态方法的类的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29727942/

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