嗨。我正在制作这个简单的字符串类,想知道是否有更自然的方法。
class Str{
function __construct($str){
$this->value = $str;
$this->length = strlen($str);
..
}
function __toString(){
return $this->value;
}
..
}
所以现在我必须像这样使用它:
$str = new Str('hello kitty');
echo $str;
但是加上括号看起来不太“自然”。所以我想知道这样的事情或类似的事情是否可能。
$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??
在第二种方法中,有没有一种方法可以再次捕获该变量 bing 集,而不是将其重置,而是将其设置为 Str::$value ?我已经考虑过,我能想到的最接近的是 __destruct 方法。但没有办法知道它是如何被摧毁的。这是可能的还是我在浪费时间?
最佳答案
由于 PHP 是松散类型的,因此没有自然 字符串类,因为使用字符串的自然方式就是直接使用它们。然而,从 PHP5.3 开始,SPL 中有一个扩展提供强类型标量:
但是请记住,此扩展标记为实验性的并且可能会发生变化。截至目前,它在 Windows 上也不可用。
您可能还想尝试 https://github.com/nikic/scalar_objects
This extension implements the ability to register a class that handles the method calls to a certain primitive type (string, array, ...). As such it allows implementing APIs like $str->length().
关于php - 如何在 PHP 中创建一个自然的 String 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2391768/