Знать точку окончания метода сцепления в php oop

Вы можете мне помочь?

пожалуйста, дайте мне знать точку окончания цепочки?

например:

class A {
     // some static function
}
A::string()->hash() // return 'abcd'
A::string()->hash()->replace('a','z') // return 'zbcd'
A::string()->hash()->replace('a','z')->sub(0,2) // return 'zb'

Как я могу написать функцию?

2 ответа

Статический метод string это фабричный метод. Он используется для создания нового экземпляра класса. Остальные методы должны возвращать сам объект, чтобы поддерживать цепочку. Кроме того, путем реализации __toString метод, объект может быть напечатан или объединен в строку.

class A {
    protected $string;

    public function __construct($string = null)
    {
        $this->string = $string;
    }
    public static function string($string = 'abcd')
    {
        return new self($string);
    }
    public function hash()
    {
        return $this;
    }
    public function replace($search, $replace)
    {
        $this->string = str_replace($search, $replace, $this->string);
        return $this;
    }
    public function sub($start, $count)
    {
        $this->string = substr($this->string, $start, $count);
        return $this;
    }
    public function toString()
    {
        return $this->string;
    }
    public function __toString()
    {
        return $this->toString();
    }
}

echo A::string()->hash(); // prints 'abcd'
echo A::string()->hash()->replace('a','z'); // prints 'zbcd'
echo A::string()->hash()->replace('a','z')->sub(0,2); // prints 'zb'

Возможно, вы захотите выполнить различные операции с входной строкой, связав столько методов, сколько захотите. Тогда у вас может быть метод, который при вызове возвращает окончательное содержимое строки после манипуляции. Возможно, вы захотите сохранить результат этой операции в переменной без необходимости отображать его в браузере. Вот способ, которым вы можете достичь этого

<?php

class A {

    /**
    *@var string The string to manipulate
    */
    private static $string;

    /**
    *This method replaces parts of a string with another string value.
    *@param string $string The string whose content is to be searched and replaced
    *@param string $search The string to search for in the $string
    *@param string $replace The string to replace with the $search string
    *@param \Object This static class
    */
    public static  function replace($string = null, $search, $replace)
    {
        //check if input string is provided and set the value of the string property
        if($string !== null) self::$string = $string;

        //evaluate and set the value of the string property
        self::$string = str_replace($search, $replace, self::$string);

        //return this static class
        return new static;
    }

    /**
    *This method returns part of the string.
    *@param string $string The string whose part is to be returned
    *@param int $start Where to start truncating from
    *@param int $count The number of characters to return from the starting point
    *@param \Object This static class
    */
    public static  function sub($string = null, $start, $count)
    {
        //check if input string is provided and set the value of the string property
        if($string !== null) self::$string = $string;

        //evaluate and set the value of the string property
        self::$string = substr(self::$string, $start, $count );

        //return this static class
        return new static;
    }

    /**
    *This method returns the final string after manipulation.
    *@param null
    *@return string The value of $string property
    */
    public static function get()
    {
       //return the contents of the string property 
       return self::$string;
    }

}

//here are the options you can have
$string = A::replace($string, $search, $replace)->sub($start, $count)->get(); //replace, get substring and return string
$string = A::replace($string, $search, $replace)->get(); //replace and return string
$string = A::sub($string, $start, $count)->replace($search, $replace)->get(); //get substring, replace and return string
$string = A::sub($string, $start, $count)->get(); //get substring and return string
?>

С этим классом вы не должны быть вынуждены echo чтобы получить содержимое последней строки, просто сохраните ее в переменной и используйте по своему усмотрению. Этот класс позволяет вам связывать методы и затем вызывать последний get() завершить цепочку и вернуть окончательное строковое значение. Вы можете вызывать метод в любом порядке A::replace()->sub()->get() или же A::sub()->replace()->get() вызывая get() как последний, чтобы завершить цепочку. Вам нужно только передать $string Значение один раз с первым методом, который вы вызываете, и его значение будет сохранено для других связанных методов. Так, например, вы бы сделали это A::replace($string, $search, $replace)->sub($start, $count)->get() или же A::sub($string, $start, $count)->replace($search, $replace)->get()

Другие вопросы по тегам