If class properties are stored as variables or in an array

I have been using php for a while, and I always wondered which one is best stored in a class.

The first way is to store data as properties.

class Foo{
    private $id;
    private $name;

    function __get($var){
        return $this->$var;
    }
}

Another method is to store data in a single array, and then use magic methods to extract it as a regular variable in the class.

class Bar{
    private $data;

    function __get($var){
        return $this->data[$var];
    }
}

Since both methods will achieve the same goal, which one is better, and why?

+3
source share
2 answers

, . () , - Traversable, .
, :
, , ,

, , PHP "" (O (1) vs O (n) ). , __get __set. . :

class Declared
{
    private $foo = 123;
    public function setFoo($val)
    {
        $this->foo = (int) $val;
        return $this;
    }
    public function getFoo()
    {
        return $this->foo;
    }
    public function __get($name)
    {
        $name = 'get'.ucfirst($name);
        if (method_exists($this, $name))
        {
            return $this->{$name}():
        }
        //return null or throw exception
        throw new RuntimeExcpetion('attempted to access non-existing property using '.$name.' in '.__METHOD__);
    }
    public function __set($name, $val)
    {
        $mname = 'set'.ucfirst($name);
        if (method_exists($this, $mname))
        {
            return $this->{$mname}($val):
        }
        throw new RuntimeException($name.' is an invalid property name');
    }
}

, , , , - , / . $foo , , int. __set, messier, ( if else).

, , :

class NotDeclared
{
    private $data = array('foo' => 123);
    public function __get($name)
    {
        return isset($this->data[$name]) ? $this->data[$name] : null;
    }
    public function __set($name, $value)
    {
        $this->[$data] = $value;
    }
}

, , . , :

$declared = new Declared;
$notDeclared = new NotDeclared;
echo $declared->foo;//ok
echo $declared->getFoo();//ok
echo $notDeclared->foo;//ok
$declared->foo = 34;//fine
$declared->setFoo($declared->foo*2);//just fine
echo $declared->fo;//TYPO => exception
echo $notDeclared->fo;//no errors show, but echoes nothing: invisible bug?
//Worse, still: 2 mistakes in one go
$notDeclared->fo = 'Typo, meant foo, but assign string to expected integer property';
$declared->fo = 'asd';//throws excpetion at once
//singe $notDeclared->fo didn't throw excpetions, I'm assuming I reassigned $foo, yet
echo $notDeclared->foo;//ecoes old value

__set, excpetions, , excpetion. , , , , , , fo

: , :

$instance->newProperty;

?

  • , newProperty
  • newProperty ( )
  • __get
  • invoke __get
    • ($this->data)
    • newProperty (isset)
    • (.. null)

, $instance->newProperty PHP newPropery, __get, $data, newPropery , null , .
.

+3

OO.

Magic get . .

, get_name(), get_id() .

, , , . , , , php , , $this->data[$var]

. , , . , , ?

0

All Articles