开发者

__set/__get with array properties

开发者 https://www.devze.com 2023-03-03 19:30 出处:网络
Wondering if it\'s possible to do something like the following (I know the code won\'t work as intended, just trying to get the purpose across):

Wondering if it's possible to do something like the following (I know the code won't work as intended, just trying to get the purpose across):

class Form
{
    private $v = array();

    function __set($varName, $varValue)
    {
        ... do some treatment on the varValue ...
        $this->v[$varName] = $varValue;
    }

    function &__get($varName)
    {
        if(!isset($this->v[$varName]))
            $this->v[$varName] = NULL;

        return $this->v[$varName];
    }
};

I want to be able to set a variable like:

$form->Values['whatever'] = 'dirty';

and have it run through the setter function which would call some cleaning operations and actually end up filling a couple other arrays like 'HtmlValues' and 'SqlValues' so I can just pull the values encoded for the format I want, so I can later call

echo $form->HtmlValues['whatever'];

The problem is of course the normal issue that if you just use _get, you get end up setting a value that's returned, and even though &_get returns it by reference and thing kind of work, __set is never actually called, even though you开发者_运维百科're setting a private member.

So basically, I'm wondering if there's a way to call a function on a value whenever you set it within an array (potentially multiple arrays deep and what not like $form->Values['group']['item'] = 'whatever';

The desired output would be something like:

$form->Values['name'] = "&";
echo $form->HtmlValues['name']; = &

(Just to reinforce, I'm not looking for the actual encoding, just the ability to call it on every variable as it's set/changed without having to encode the entire array manually)


You want to implement the ArrayAccess interface. the linked page has examples on how to do this.

EDIT: For ease of access, I have included the example from php.net below:

<?php
class obj implements arrayaccess {
    private $container = array();
    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }
    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }
    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }
    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }
    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>


Take a look at ArrayAccess.


What I do in this situation is have the __get() return an object that extends ArrayObject instead of the array directly.

private $v;
public function __construct()
{
  $this->v = new ArrayObject(); // or MyArrayObject()
  // repeat for each of your "arrays" you want to return
}

(Note that this is different from implementing ArrayAccess directly by the parent class, which can also be useful in other situations.)

Here's an example:

<?php
class MyArrayObject extends ArrayObject
{
  private $validate;
  public function __construct($validate)
  {
    parent::__construct();
    $this->validate = $validate;
  }

  public function offsetSet($i, $v)
  {
    $validate = $this->validate;
    if (!$validate($this, $i, $v))
      throw new Exception();

    parent::offsetSet($i, $v);
  }
}

class Foo
{
  private $v;
  public function __construct()
  {
    $this->v = new MyArrayObject(function(MyArrayObject $me, $i, $v) {
      // only accept values that are larger than 5
      return $v > 5;
    });
  }

  public function __get($key)
  {
    if ($key == 'bar') return $this->v;
  }
}

$f = new Foo();
$f->bar[] = 10;
$f->bar[] = 5;   // throws exception
0

精彩评论

暂无评论...
验证码 换一张
取 消