开发者

php objects define and set attributes in constructor

开发者 https://www.devze.com 2022-12-11 07:01 出处:网络
Is it possible to define attributes to a class 开发者_Python百科in the constructor. For instance I pass a Associative Array to a class constructor and I want the attributes to that class to be declare

Is it possible to define attributes to a class 开发者_Python百科in the constructor. For instance I pass a Associative Array to a class constructor and I want the attributes to that class to be declared and set based on what is in the Associative Array.

TIA


class Foo{
   function __construct($arr){
       foreach($arr as $k => $v)
          $this->$k = $v;
   }
}

You can review the constructor/desctructor manual and properties manual.

to be noted since you don't define the properties in the class all are set to public which IMHO is kind of dangerous. I think it might be possible to achieve the same thing using the reflection. I just checked more in depth the reflection and it is not possible (with PHP5), since it would make sense to be able to do that from the reflection it might come with PHP6.

full sample

<?php
class Foo{
   function __construct($arr){
       foreach($arr as $k => $v)
          $this->$k = $v;
   }

   function getBar(){
       return $this->bar;
   }
}

$bar = new Foo(array(
    'bar' => 'bar',
    'foo' => 'foo'
)
);

var_dump($bar->bar);
?>


Yes, you can do that. off top of my head

public function __constructor($data){
  foreach($data as $k=>$v){
     $this->{$k} = $v;
  }
}

This should do it, and of course you need to math define the fields.

I m not too sure if it s {$k} or ${k} or ${$k} but either of these should work.


You can certainly do this, as RageZ describes above, but I don't think I would recommend doing it. What this does is creates too loose of a "contract" between the users of this class - i.e. nobody really knows which properties the class has.

Instead of defining the properties on the fly, I would bet that you have a pre-defined set of "object property sets" that could in turn define a class hierarchy.

So instead of doing

  • if I get an array with "a = 2 and b = 3", create object with $obj->a = 3 and $obj-b = 3
  • if I get an array with "c = 5", create an object with $obj->c = 5

Do this:

  • define a class for MyObjectOfTypeOne, that has properties $a and $b
  • define a class for MyObjectOfTypeTwo that has property $c

Then, use the Factory pattern to generate the right type of object depending on the parameters passed to the static factory method.

0

精彩评论

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