9
 $model = new static($variable);

所有这些都在一个类的方法中,我试图从技术上理解这段代码的作用。我在谷歌世界里跑来跑去。但是找不到任何可以让我找到答案的东西。这只是另一种说法吗。

 $model = new static $variable;

还有这个怎么办

 $model = new static;

这是否意味着我正在初始化一个变量并将其值设置为 null 但我只是在运行该方法后保留该变量以不丢失该值?

4

5 回答 5

11

在这种情况下,静态表示当前对象范围。它用于后期静态绑定。

通常这与使用self. 它不同的地方是当你有一个对象层次结构时,对范围的引用是在父级上定义的,但在子级上被调用。在这种情况下,self 将引用父母的范围,而 static 将引用孩子的范围

class A{
    function selfFactory(){
        return new self();
    }

    function staticFactory(){
        return new static();
    }
}

class B extends A{
}


$b = new B();

$a1 = $b->selfFactory(); // a1 is an instance of A

$a2 = $b->staticFactory(); // a2 is an instance of B

最容易将 self 视为定义范围,将 static 视为当前对象范围。

于 2013-06-07T06:20:29.283 回答
4

self只是它所在的类的“快捷方式名称”。static是它较新的后期静态绑定表亲,它总是引用当前类。即当扩展一个类时,static如果从子上下文中调用,也可以引用子类。

new static只是意味着创建当前类的新实例,并且只是new self.

是的,static== 更有活力很奇怪的。

于 2013-06-07T06:54:36.330 回答
2

您必须将它放在一个类的上下文中,其中static是对调用它的类的引用。我们可以选择$variable其作为参数传递给__construct您正在创建的实例的函数。

像这样:

class myClass {

    private $variable1;

    public function __construct($variable2) {
        $this->variable1 = $variable2;
    }

    public static function instantiator() {
        $variable3 = 'some parameter';
        $model = new static($variable3); // <-this where it happens.
        return $model;
    }
}

这里static指的是myClass,我们将变量'some parameter'作为参数传递给__construct函数。

于 2017-06-30T04:31:52.260 回答
0

您可以使用new static()从类中实例化一组类对象,并使其与类的扩展一起使用。

class myClass {
  $some_value = 'foo';
  public function __construct($id) {
    if($this->validId($id)) {
      $this->load($id); 
    }
  }

  protected function validId($id) {
    // check if id is valid.
    return true; // or false, depending
  }

  protected function load($id) {
    // do a db query and populate the object's properties
  }

  public static function getBy($property, $value) {
    // 1st check to see if $property is a valid property
    // if yes, then query the db for all objects that match
    $matching_objects = array();
    foreach($matching as $id) {
      $matching_objects[] = new static($id); // calls the constructor from the class it is called from, which is useful for inheritance.
    }
    return $matching_objects;
  }
}


myChildClass extends myClass {
  $some_value = 'bar'; // 
}


$child_collection = myChildClass::getBy('color','red'); // gets all red ones

$child_object = $child_collection[0];

print_r($child_object); // you'll see it's an object of myChildClass
于 2013-06-07T07:00:32.810 回答
-2

关键字 new 用于创建已定义类的对象

$模型=新静态($变量);

所以这里有一个创建的模型对象,它是静态类的一个实例

于 2013-06-07T06:11:09.520 回答