>  기사  >  백엔드 개발  >  PHP 체인 호출

PHP 체인 호출

WBOY
WBOY원래의
2016-08-08 09:06:531307검색

strlen (strim ($str))문자열의 길이를 구하는 함수입니다. 어떻게 연쇄 연산으로 쓸 수 있나요?

<code>$str -> trim() -> strlen()</code>

팁:

먼저 String 클래스를 구현하여 처리를 위해 이 클래스의 객체를 호출하면 __call 매직 메서드가 트리거된 후 call_user_func가 실행됩니다.

답글 내용:

strlen (strim ($str))문자열의 길이를 구하는 함수인데 어떻게 연쇄 연산으로 쓸 수 있나요?

<code>$str -> trim() -> strlen()</code>

팁:

먼저 String 클래스를 구현하여 처리를 위해 이 클래스의 객체를 호출하면 __call 매직 메서드가 트리거된 후 call_user_func가 실행됩니다.

소스코드는 다음과 같습니다

<code class="php"><?php
/**
 * 字符串处理
 *
 * @author Flc <2016-08-04 23:39:41>
 * @link http://flc.ren
 */
class Str
{
    /**
     * 字符串
     * @var [type]
     */
    protected $string;

    /**
     * 支持的函数
     * @var array
     */
    protected $methods = ['trim', 'strlen'];

    /**
     * 初始化
     * @param [type] $string [description]
     */
    public function __construct($string)
    {
        $this->string = $string;
    }

    /**
     * 单例模式
     * @param  string $string 字符串
     * @return Object:Str         
     */
    public static function getInstance($string)
    {
        static $_instances = [];

        if (isset($_instances[$string]))
            return $_instances[$string];

        return $_instances[$string] = new self($string);
    }

    /**
     * 输出
     * @return string 
     */
    public function response()
    {
        return $this->string;
    }

    /**
     * 模式方法
     * @param  string $method 方法
     * @return Object:Str         
     */
    public function __call($method, $args)
    {
        if (in_array($method, $this->methods)) {
            if (function_exists($method)) {
                $this->string = call_user_func($method, $this->string);
            }
        }

        return $this;
    }
}

// DEMO
echo Str::getInstance(' 123123 123')->trim()->strlen()->response();
?></code>

<code><?php
/**
 * Created by PhpStorm.
 * User: hongxu
 * Date: 16/8/4
 * Time: 13:21
 */

class str {

    private $str = '';

    /**
     * str constructor.
     */
    public function __construct($str) {

        $this->str = $str;
    }

    public function trim() {
        $this->str = trim($this->str);
        return $this;
    }

    public function strlen() {
        return strlen($this->str);
    }
}

$str = new str('要思考,不做伸手党');

var_dump($str->trim()->strlen());die;</code>

출력:

<code>php test.php
int(25)
</code>

<code class="php"><?php
class Str {
    private $value = '';

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

    public function __call($name, $args) {
        if (function_exists($name)) {
            array_unshift($args, $this->value);
            $value = call_user_func_array($name, $args);
            if (is_string($value)) {
                return new static($value);
            } else {
                return $value;
            }
        }
    }

    public function __toString() {
        return $this->value;
    }
}

$str = new Str('  题主是不是个伸手党?  ');

echo($str->trim() . PHP_EOL);
echo($str->trim()->strlen() . PHP_EOL);
$trim_str = $str->trim();
echo($trim_str->substr(0, $trim_str->strlen() - 1) . PHP_EOL);</code>
<code>题主是不是个伸手党?
28
题主是不是个伸手党</code>

이러한 기능을 구현하는 것은 어렵지 않습니다. 문자열을 캡슐화하기만 하면 됩니다. 체인 호출이 필요한 경우 $this를 반환하면 됩니다.
기능을 구현하려면 다음 코드를 참조하세요.

<code><?php
//演示链式调用

class MyString{
    private $string;
    
    function MyString($str){
        $this->string=$str;
    }
    
    function len(){
        return strlen($this->string);
    }
    
    function _trim(){
        $this->string=trim($this->string);
        return $this;
    }
}

$d=new MyString(' sdfsdf  ');
echo $d->_trim()->len();
?></code>

->왜 공백이 필요한가요 == 이상해 보이네요

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.