Php 向对象动态添加私有属性
我有一门课:Php 向对象动态添加私有属性,php,oop,Php,Oop,我有一门课: class Foo { // Accept an assoc array and appends its indexes to the object as property public function extend($values){ foreach($values as $var=>$value){ if(!isset($this->$var)) $this->$var
class Foo {
// Accept an assoc array and appends its indexes to the object as property
public function extend($values){
foreach($values as $var=>$value){
if(!isset($this->$var))
$this->$var = $value;
}
}
}
$Foo = new Foo;
$Foo->extend(array('name' => 'Bee'));
现在,$Foo
对象有一个值为Bee
的公共name
属性
如何更改扩展
函数以使变量私有
编辑
使用私有数组是另一种方法,肯定不是我的答案。您可以这样做
\uu get
功能将检查给定的键是否设置在
私有财产
class Foo {
private $data = array();
// Accept an array and appends its indexes to the object as property
public function extend($values){
foreach($values as $i=>$v){
if(!isset($this->$i))
$this->data[$i] = $v;
}
}
public function __get($key) {
if (isset($this->data[$key])) {
return $this->data[$key];
}
}
}
我将使用整个阵列:
$Foo = new Foo;
$Foo->setOptions(array('name' => 'Bee'));
class Foo {
private $options = array();
public function setOptions(array $options) {
$this->options = $options;
}
public function getOption($value = false) {
if($value) {
return $this->options[$value];
} else {
return $this->options;
}
}
}
然后,当您需要其他值时,您就有了更多的选项,您可以遍历数组并使用它们。在大多数情况下,只有一个变量有点复杂。只是简单、糟糕的设计 在运行时添加私有[!]字段的目的是什么?现有的方法不能依赖于这样添加的字段,而且您会弄乱对象功能
<如果你希望你的对象表现得像一个哈希图(即,你可以只调用<代码> $Obj-> NeWield= $ NealValue/Cult>),考虑使用魔法>代码>
class Extendible
{
private $properties;
public function extend(array $properties)
{
foreach ($properties as $name => $value) {
$this->properties[$name] = $value;
}
}
public function __call($method, $parameters)
{
$accessor = substr($method, 0, 3);
$property = lcfirst(substr($method, 3));
if (($accessor !== 'get' && $accessor !== 'set')
|| !isset($this->properties[$property])) {
throw new Exception('No such method!');
}
switch ($accessor) {
case 'get':
return $this->getProperty($property);
break;
case 'set':
return $this->setProperty($property, $parameters[0]);
break;
}
}
private function getProperty($name)
{
return $this->properties[$name];
}
private function setProperty($name, $value)
{
$this->properties[$name] = $value;
return $this;
}
}
演示:
为什么不将整个数组存储到私有属性中?$i和$var不应该是同一个变量吗?@Lewyx:是的,只是一个错误,经过编辑。@jackflash这是另一种解决方案,但会改变问题。好吧,那你就不能了。不可能在运行时添加私有属性。这是另一种方法,而不是我的答案。实际上,这是创建不可变对象的好方法。它的行为就像一个常量的大集合。但有了key=>val的好处,值可以是标量、[]、{}。。。
try {
$x = new Extendible();
$x->extend(array('foo' => 'bar'));
echo $x->getFoo(), PHP_EOL; // Shows 'bar'
$x->setFoo('baz');
echo $x->getFoo(), PHP_EOL; // Shows 'baz'
echo $x->getQuux(), PHP_EOL; // Throws Exception
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), PHP_EOL;
}