PHP and MagicMethods


PHP and MagicMethods

我写了一些类来处理类似C#中的字符串。

这是:

class String {
        private $origin_string = null;
        private $result_string = null;
        function __construct($string)
        {
            $this->origin_string = $string;
            $this->result_string = $this->origin_string;
        }
        public function Trim()
        {
            $this->result_string = Trim($this->result_string);
            return $this->result_string;
        }
        public function StartWith($string)
        {
            return (substr($this->result_string, 0, strlen($string)) === $string);
        }
        public function EndWith($string)
        {
            $endlen = strlen($string);
            $strlen = strlen($this->result_string);
            return (substr($this->result_string, $strlen - $endlen, $endlen) === $string);
        }
        public function Contains($string) {
            return (strpos($this->result_string, $string) !== false);
        }
        public function Replace($search, $string) {
            $this->result_string = str_replace($search, $string, $this->result_string);
            return $this->result_string;
        }
        public function __invoke($string) {
            $this->origin_string = $string;
            $this->result_string = $this->origin_string;
            return $this;
        }
        public function __toString()
        {
            return $this->result_string;
        }
        public static function Override($string)
        {
            return new self($string);
        }
    }

使用中:

$s = new String("My custom string");
if ($s->StartWith("My"))
    $s->Replace("custom", "super");
print $s; // "My super string"

为了更正从对象打印的文本,我使用了魔术方法__toString()。

问题:有一个方法,逆__toString吗?这样我们就可以写:

$s = "new text";

这条线被指定给对象中的变量。

($s-上面例子中的一个现有对象"String"。)

方法__set的类似物,仅与对象有关,而不是与对象内部的变量有关。

在使用__invoke时,但这不是我想要的。

否。

$s = "new text";将(本机PHP)字符串"new text"分配给变量$s。它覆盖了$s之前的内容。如果$s是一个对象,则它不调用$s上的任何方法。

你必须改变PHP的核心行为才能达到这样的效果。您总是必须显式地调用String对象上的方法。

直接问题的简短答案是"不,在PHP中没有任何方法可以做到这一点"。

字符串是PHP中的一种基本数据类型,它不执行运算符重载或任何其他启用此类功能所需的功能。

但是,因为它们是一种原始数据类型,所以没有必要将它们封装在这样的对象结构中。PHP的OO功能在最近的版本中取得了长足的进步,但从本质上讲,它仍然不是一种完全的OO语言。

事实上,我认为你所做的是适得其反的。您正在将字符串的概念封装到一个比基本PHP功能少得多的类中。你在写一大堆代码,以便在一行代码中完成已经可以在一行码中完成的事情,这限制了你做更多事情的能力。

例如,您有Contains()StartsWith()方法,但它们不以任何方式处理正则表达式。

你将如何处理串联?那么把变量嵌入字符串呢?

PHP有很多字符串处理功能(事实上,字符串处理是它的优势之一),而您的类无法复制这些功能。

我建议您使用给定的语言,而不是试图强迫它符合您的语法理想。

不,不能直接为对象赋值。PHP不允许运算符重载和这种样式赋值。必须使用构造函数、invoke或任何setter方法为字符串分配一个新值。

你可以写这样的东西:

$s = 'myclass';
$o = new $s();

或者,如果你想"编译"新的关键字,你可以做:

$s = '$x = new myclass();';
eval($s);

希望这能有所帮助。