PHP   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP:提供静态和非静态方法的类的设计模式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是创建可以静态和非静态方式使用的类.两种方式都必须使用相同的方法,但方式不同

非静态方式:

$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).

callStatic

另一种可能性是使用魔术方法__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,$arguments
        );
        return $color;

    }
}

请注意,这有点凌乱.就个人而言,我不会使用这种方法,因为它对你的类的用户来说不是那么好(你甚至没有合适的phpDocs).对于程序员来说,这是最简单的,因为在添加新函数时不需要添加大量额外代码.

大佬总结

以上是大佬教程为你收集整理的PHP:提供静态和非静态方法的类的设计模式全部内容,希望文章能够帮你解决PHP:提供静态和非静态方法的类的设计模式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。