[英]How to create a class only for string manipulation and usable in all other classes for specific manipulations that repeats in other classes
我有一堂课:
class Users { ... }
我希望在某些方法中将字符串操纵为小写/大写/驼峰式等,而不必重写在我拥有的所有其他类中都能做到的方法。
因此,我想创建一个“字符串”类(或接口?还是静态类?),并重用其他类(例如, class Apps { ... }
)中的功能,这些功能仅用于计算或字符串操作。
我曾经做过新的事情,但记不清了。
您可能正在寻找特质( http://php.net/manual/en/language.oop5.traits.php )
<?php
trait StringUtils
{
protected function toLower($value)
{
return mb_strtolower($value);
}
protected function toUpper($value)
{
return mb_strtoupper($value);
}
}
class User
{
use StringUtils;
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function displayName()
{
return $this->toLower($this->name);
}
}
$me = new User('Rick');
echo $me->displayName(); // rick
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.