我一直在修补PHP以学习一些新东西(希望如此),我想知道,使用这些类代替字符串有什么优点/缺点:
class Str
{
protected $value = "";
public function __construct($string)
{
if (is_string($string)) {
$this->value = $string;
return true;
} else {
return false;
}
}
public function contains($needle)
{
return strpos($this->value, $needle) !== false;
}
public function startsWith($needle)
{
return substr($this->value, 0, strlen($needle)) === $needle;
}
public function endsWith($needle)
{
return substr($this->value, -strlen($needle)) === $needle;
}
public function value()
{
return $this->value;
}
}
这比静态方法调用更易于测试。除此之外,做这样的事情没有问题,也没有明显可见的优势/劣势。事实上,有一个实用程序包可以完全完成您正在做的事情。看看Stringy。
好吧,仅仅通过看到这个类,我们无法告诉你它是否有用。我可以告诉你,面向对象编程比过程编程更好。
如果你想找出为什么会这样,我建议阅读这个问题和答案。