这样的课程有什么好处吗?
Is there any advantages to classes like these?
我一直在研究 PHP 以学习一些新东西(希望如此),我想知道是否有任何 advantages/disadvantages 可以使用像这样的类来代替字符串:
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;
}
}
嗯,仅仅看到这个 class 我们不能告诉你它是否有用。我可以告诉你,面向对象编程比面向过程编程更好。
如果您想了解这是为什么,我建议您阅读 this 问答。
这比静态方法调用更易于测试。除此之外,做这样的事情没有问题,并且没有 advantage/disadvantage 清晰可见。事实上,有一个实用程序包可以完全满足您的需求。看看Stringy.
我一直在研究 PHP 以学习一些新东西(希望如此),我想知道是否有任何 advantages/disadvantages 可以使用像这样的类来代替字符串:
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;
}
}
嗯,仅仅看到这个 class 我们不能告诉你它是否有用。我可以告诉你,面向对象编程比面向过程编程更好。
如果您想了解这是为什么,我建议您阅读 this 问答。
这比静态方法调用更易于测试。除此之外,做这样的事情没有问题,并且没有 advantage/disadvantage 清晰可见。事实上,有一个实用程序包可以完全满足您的需求。看看Stringy.