开发者

jQuery style Constructors in PHP

开发者 https://www.devze.com 2023-02-03 21:10 出处:网络
Is there a way to instantiate a new PHP object in a similar manner to those in jQuery?I\'m talking about assigning a variable number of arguments when creating the object.For example, I know I could d

Is there a way to instantiate a new PHP object in a similar manner to those in jQuery? I'm talking about assigning a variable number of arguments when creating the object. For example, I know I could do something like开发者_JS百科:

...
//in my Class
__contruct($name, $height, $eye_colour, $car, $password) {
...
}

$p1 = new person("bob", "5'9", "Blue", "toyota", "password");

But I'd like to set only some of them maybe. So something like:

$p1 = new person({
    name: "bob",
    eyes: "blue"});

Which is more along the lines of how it is done in jQuery and other frameworks. Is this built in to PHP? Is there a way to do it? Or a reason I should avoid it?


the best method to do this is using an array:

class Sample
{
    private $first  = "default";
    private $second = "default";
    private $third  = "default";

    function __construct($params = array())
    {
         foreach($params as $key => $value)
         {
              if(isset($this->$key))
              {
                  $this->$key = $value; //Update
              }
         }
    }
}

And then construct with an array

$data = array(
     'first' => "hello"
     //Etc
);
$Object = new Sample($data);


class foo {
   function __construct($args) {
       foreach($args as $k => $v) $this->$k = $v;
       echo $this->name;
    }
 }

 new foo(array(
    'name' => 'John'
 ));

The closest I could think of.

If you want to be more fancy and just want to allow certain keys, you can use __set() (only on php 5)

var $allowedKeys = array('name', 'age', 'hobby');
public function __set($k, $v) {
   if(in_array($k, $this->allowedKeys)) {
      $this->$k = $v;
   }
}


get args won't work as PHP will see only one argument being passed.

public __contruct($options) {
    $options = json_decode( $options );
    ....
    // list of properties with ternary operator to set default values if not in $options
    ....
}

have a looksee at json_decode()


The closest I can think of is to use array() and extract().

...
//in your Class
__contruct($options = array()) {

    // default values
    $password = 'password';
    $name = 'Untitled 1';
    $eyes = '#353433';

    // extract the options
    extract ($options);

    // stuff
    ...

}

And when creating it.

$p1 = new person(array(
    'name' => "bob",
    'eyes' => "blue"
));
0

精彩评论

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