在 PHP 中为 setter 方法赋值

发布于 2024-11-10 17:52:21 字数 1016 浏览 5 评论 0原文

我有这个类,让我可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光是把杀猪刀 2024-11-17 17:52:21

如果数据是公开的而不是私有的,您可以这样做。私有意味着只有对象可以在内部获取该值。公众会允许你这样做。要么创建一个方法来执行您想要的操作,因为这可以在内部访问数组,从而使数据保持私有。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文