PHP new static($ variable)

时间:2013-06-07 06:09:17

标签: php static

 $model = new static($variable);

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

 $model = new static $variable;

还有这个

 $model = new static;

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

6 个答案:

答案 0 :(得分:9)

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

通常这与使用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视为当前对象范围。

答案 1 :(得分:3)

self只是它所出现的类的“快捷方式名称”。static是其较新的late static binding表兄弟,它总是引用当前类。即扩展类时,如果从子上下文调用,static也可以引用子类。

new static只是意味着制作当前类的新实例,而且只是new self的动态表亲。

是的,static ==更动态的 很奇怪。

答案 2 :(得分:2)

请查看以下链接,了解新的Static()。

New self vs. new static

答案 3 :(得分: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函数。

答案 4 :(得分: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

答案 5 :(得分:-2)

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

的对象

$ model = new static($ variable);

所以这里有一个创建模型的对象,它是类static

的一个实例