【问题标题】:Php run method on property change关于属性更改的php运行方法
【发布时间】:2016-01-26 19:55:48
【问题描述】:

是否可以在属性更改时运行 php 方法?如下例所示:

类:

class MyClass
{
    public MyProperty;

    function __onchange($this -> MyProperty)
    {
        echo "MyProperty changed to " . $this -> MyProperty;
    }        
}

对象:

$MyObject = new MyClass;
$MyObject -> MyProperty = 1;

结果:

 "MyProperty changed to 1"

【问题讨论】:

  • 将变量设为私有并使用函数对其进行更改。
  • 你必须实现它。例如更改属性,触发事件并捕获事件。

标签: php class object methods properties


【解决方案1】:

就像@lucas 所说,如果您可以在类中将您的属性设置为私有,那么您可以使用 __set() 来检测更改。

class MyClass
{
  private $MyProperty;

  function __set($name, $value)
  {
     if(property_exists('MyClass', $name)){
       echo "Property". $name . " modified";
     }
  }

 }


$r = new MyClass;
$r->MyProperty = 1; //Property MyProperty changed.

【讨论】:

  • 不错,但会影响所有私有属性
  • 从类中更改属性时不会调用它。关于如何做这件事的任何想法?
【解决方案2】:

您可以通过使用 setter 方法来达到最佳效果。

class MyClass
{
    private MyProperty;

    public function setMyProperty($value)
    {
        $this->MyProperty = $value;
        echo "MyProperty changed to " . $this -> MyProperty;
    }

}

现在您只需调用 setter,而不是自己设置值。

$MyObject = new MyClass;
$MyObject -> setMyProperty(1);

【讨论】:

    【解决方案3】:

    使用magic method __set

    class Foo {
    
        protected $bar;
    
        public function __set($name, $value) {
            echo "$name changed to $value";
            $this->$name = $value;
        }
    
    }
    
    $f = new Foo;
    $f->bar = 'baz';
    

    使用一个好的老式 setter 可能是一个更好、更传统的想法:

    class Foo {
    
        protected $bar;
    
        public function setBar($value) {
            echo "bar changed to $value";
            $this->bar = $value;
        }
    
    }
    
    $f = new Foo;
    $f->setBar('baz');
    

    【讨论】:

      【解决方案4】:

      这篇文章很老了,但我必须处理同样的问题和一个具有多个字段的典型类。为什么使用私有属性? 这是我实现的:

      class MyClass {
      
          public $foo;
          public $bar;
      
          function __set($name, $value) {
              if(!property_exists('MyClass', $name)){ // security
                  return;
              }
              if ('foo' == $name) { // test on the property needed to avoid firing 
                                    // "change event" on every private properties
                  echo "Property " . $name . " modified";
              }
              $this->$name = $value;
          }
      
      }
      
      $r = new MyClass();
      $r->bar = 12;
      $r->foo = 1; //Property foo changed.
      var_dump($r);
      /*
      object(MyClass)[1]
        public 'foo' => int 1
        public 'bar' => int 12
      */
      

      【讨论】:

      • 这不起作用,因为 foo 属性必须是受保护的或私有的才能调用 setter。如果公开,它只会更改值并绕过 __set 方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      相关资源
      最近更新 更多