加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:30:14 所属栏目:PHP教程 来源:网络整理
导读:海.我正在制作这个简单的字符串类,并想知道是否有更自然的方法. class Str{ function __construct($str){ $this-value = $str; $this-length = strlen($str); .. } function __toString(){ return $this-value; } ..} 所以现在我必须像这样使用它: $str = n
海.我正在制作这个简单的字符串类,并想知道是否有更自然的方法.
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 set而不是重置它,将其设置为Str :: $value?我已经考虑过了,我最接近的是__destruct方法.但没有办法知道它是如何被摧毁的.这可能还是我在浪费时间?

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

> http://php.net/manual/en/book.spl-types.php

但是,请记住,此扩展程序标记为实验性的,可能会发生变化.截至目前,它在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().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读