在 PHP 中为 setter 方法赋值
我有这个类,让我可以使用 setData
方法更改私有 data
属性:
abstract class FooBase{
public function __set($name, $value){
$setter = 'set'.ucfirst($name);
if(method_exists($this, $setter)) return $this->$setter($value);
throw new Exception("Property {$setter} is not defined.");
}
}
class Foo extends FooBase{
static $instance;
private $data;
public static function app(){
if(!(self::$instance instanceof self)){
self::$instance = new self();
self::app()->data = array('a' => 'somedata', 'b' => 'moredata');
}
return self::$instance;
}
public function setData($newdata){
$this->data = $newdata;
}
}
因此,要更改它,我将其称为:
Foo::app()- >data = array('a' => 'newdata', 'b' => 'morenewdata');
我想知道是否可以以某种方式仅更改 $data 中的一个数组值
,例如:
Foo::app()->data['a'] = 'newdata'; // <-- this doesn't work, but it's what I would like to do...
I have this class which let's me change the private data
property using the setData
method:
abstract class FooBase{
public function __set($name, $value){
$setter = 'set'.ucfirst($name);
if(method_exists($this, $setter)) return $this->$setter($value);
throw new Exception("Property {$setter} is not defined.");
}
}
class Foo extends FooBase{
static $instance;
private $data;
public static function app(){
if(!(self::$instance instanceof self)){
self::$instance = new self();
self::app()->data = array('a' => 'somedata', 'b' => 'moredata');
}
return self::$instance;
}
public function setData($newdata){
$this->data = $newdata;
}
}
So to change it I call it like:
Foo::app()->data = array('a' => 'newdata', 'b' => 'morenewdata');
I was wondering if it's possible to somehow change only one array value from $data
, like:
Foo::app()->data['a'] = 'newdata'; // <-- this doesn't work, but it's what I would like to do...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果数据是公开的而不是私有的,您可以这样做。私有意味着只有对象可以在内部获取该值。公众会允许你这样做。要么创建一个方法来执行您想要的操作,因为这可以在内部访问数组,从而使数据保持私有。
You could do this if data was public instead of private. Private means only the object can get that value internally. Public would allow you to do this. Either that or create a method to do what you want, as this could access the array internally, leaving data private.