如果我有一个将被实例化的类,需要引用每个类相同的数据和/或函数。如何处理以遵循正确的编程实践
示例(PHP):
class Column {
$_type = null;
$_validTypes = /* Large array of type choices */;
public function __construct( $type ) {
if( type_is_valid( $type ) ) {
$_type = $type;
}
}
public function type_is_valid( $type ) {
return in_array( $type, $_validTypes );
}
}
然后每次创建Column时,它将保存$_validTypes
变量。这个变量实际上只需要在内存中定义一次,其中创建的所有列都可以引用静态函数type_is_valid
,用于静态类,该静态类将包含仅声明一次的$_validTypes
变量。
是一个静态类的想法,说ColumnHelper
或ColumnHandler
一个好方法来处理这个?或者是否有一种方法在该类中保存静态数据和方法?或者这是重新定义$_validTypes
为每个列一个好的方式来做的事情?
一个选项是为列配置创建一个新模型,例如
class ColumnConfig {
private $validTypes;
public isValid($type){
return isset($this->validType($type))?true:false;
}
}
,如果你有一个,或者创建一个全局实例,例如
$cc = new ColumnConfig();
class Column {
private $cc;
function __construct($type){
$this->cc = $this->api->getCC(); // if you have api
global $cc; // assuming you have no api, an you create a global $cc instance once.
$this->cc = $cc; // <-- this would pass only reference to $cc not a copy of $cc itself.
if ($this->cc->isValid($type)){
....
}
}
}