如何在PHP中创建一个自然的String类

shx*_*fee 7 php oop string

海.我正在制作这个简单的字符串类,并想知道是否有更自然的方法.

class Str{
    function __construct($str){
        $this->value = $str;
        $this->length = strlen($str);
        ..
    }

    function __toString(){
        return $this->value;
    }
    ..
}
Run Code Online (Sandbox Code Playgroud)

所以现在我必须像这样使用它:

$str = new Str('hello kitty');
echo $str;
Run Code Online (Sandbox Code Playgroud)

但是用圆括号看起来并不那么"自然".所以我想知道这样或类似的东西是否可能.

$str = new Str 'hello kitty'; # I dont believe this is possible although this is preferred.

$str = new Str; # get rid of the construct param.
$str = 'value here'; #instead of resetting, set 'value here' to Str::$value??
Run Code Online (Sandbox Code Playgroud)

在第二种方法中,有没有办法可以再次捕获变量bing set而不是重置它,将其设置为Str :: $ value?我已经考虑过了,我最接近的是__destruct方法.但没有办法知道它是如何被摧毁的.这可能还是我在浪费时间?

Gor*_*don 8

由于PHP是松散类型的,因此没有自然的字符串类,因为使用字符串的自然方式就是使用它们.但是,从PHP5.3开始,SPL中有一个扩展,它提供强类型标量:

但是,请记住,此扩展程序标记为实验性的,可能会发生变化.截至目前,它在Windows上也不可用.

您可能还想尝试https://github.com/nikic/scalar_objects

此扩展实现了注册处理对某种基本类型(字符串,数组,...)的方法调用的类的能力.因此,它允许实现像$ str-> length()这样的API.