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

前端之家收集整理的这篇文章主要介绍了如何在PHP中创建一个自然的String类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
海.我正在制作这个简单的字符串类,并想知道是否有更自然的方法.
  1. class Str{
  2. function __construct($str){
  3. $this->value = $str;
  4. $this->length = strlen($str);
  5. ..
  6. }
  7.  
  8. function __toString(){
  9. return $this->value;
  10. }
  11. ..
  12. }

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

  1. $str = new Str('hello kitty');
  2. echo $str;

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

  1. $str = new Str 'hello kitty'; # I dont believe this is possible although this is preferred.
  2.  
  3. $str = new Str; # get rid of the construct param.
  4. $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().

猜你在找的PHP相关文章