【问题标题】:jQuery style Constructors in PHPPHP 中的 jQuery 样式构造函数
【发布时间】:2011-01-13 14:48:13
【问题描述】:

有没有办法以类似于 jQuery 的方式实例化一个新的 PHP 对象?我说的是在创建对象时分配可变数量的参数。例如,我知道我可以这样做:

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

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

但我可能只想设置其中的一些。所以像:

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

这更像是在 jQuery 和其他框架中如何完成的。这是内置在 PHP 中的吗?有没有办法做到这一点?还是我应该避免它的原因?

【问题讨论】:

标签: php oop class-constructors


【解决方案1】:

最好的方法是使用数组:

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
              }
         }
    }
}

然后用数组构造

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

【讨论】:

  • 不过,这不是他想要的。他想使用可以按任意顺序指定的命名参数
  • 是的,我正在更新中:/
  • 这次更新有一堆好资料。 +1。 (虽然我个人会为参数提供默认值,而不是让它们为空)...
【解决方案2】:
class foo {
   function __construct($args) {
       foreach($args as $k => $v) $this->$k = $v;
       echo $this->name;
    }
 }

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

我能想到的最接近的。

如果你想更花哨,只想允许某些键,你可以使用__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;
   }
}

【讨论】:

  • 可变变量?课堂内?真的吗?为什么不使用$this->$k 而不是$$k?不错的想法,错误的实现...如果您要这样做,为什么不直接使用extract? -1...
【解决方案3】:

get args 不起作用,因为 PHP 只会看到一个参数被传递。

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

看看json_decode()

【讨论】:

  • 在这种情况下使用 json 是没有意义的。 (不需要对原生数组进行不必要的编码/解码。)
  • 同意 - 但只是解决了 OP 的初始请求。无需编码 json 以传入对象实例化,但始终需要解码。
【解决方案4】:

我能想到的最接近的是使用array()extract()

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

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

    // extract the options
    extract ($options);

    // stuff
    ...

}

以及在创建它时。

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

【讨论】:

    猜你喜欢
    • 2013-06-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2010-12-15
    • 1970-01-01
    相关资源
    最近更新 更多