PHP链式操作的实现

@三种实现方法

    #魔法函数__call结合call_user_func来实现

    #使用魔法函数__call结合call_user_func_array来实现

    #return $this;

@使用魔法函数__call结合call_user_func来实现

<?php

    class StringHelper

    {

        private $value;

        function __construct($value)

        {

            $this->value = $value;

        }

        function __call($function, $args){

            $this->value = call_user_func($function, $this->value, $args[0]);

            return $this;

        }

        function strlen() {

            return strlen($this->value);

        }

    }

$str = new StringHelper("  sd f  0");

echo $str->trim('0')->strlen();

@使用魔法函数__call结合call_user_func_array来实现

    class StringHelper

    {

        private $value;

        function __construct($value)

        {

            $this->value = $value;

        }

        function __call($function, $args){

            array_unshift($args, $this->value);

            $this->value = call_user_func_array($function, $args);

            return $this;

        }

        function strlen() {

            return strlen($this->value);

        }

    }

    $str = new StringHelper("  sd f  0");

    echo $str->trim('0')->strlen();

@return $this;

public function trim($t)

{

    $this->value = trim($this->value, $t);

    return $this;

}

    

猜你喜欢

转载自blog.csdn.net/glfxml/article/details/82775421