Version php : php5.6
La liaison différée inclut : get_class($this), get_call_class(), new static(), static::
La liaison non différée inclut : get_class (), __CLASS__, new self(), self::
Lors de l'utilisation de new static()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?phpclass NewStatic{
private $newStatic ;
public function init()
{
if ( empty ( $this -> newStatic)) { $this -> newStatic = new static (); echo "该类已初始化" ;
} else { $this -> newStatic -> exec ();
}
}
public function exec ()
{
echo "该类NewStatic已执行" ;
}
} class Sub extends NewStatic{
public function exec ()
{
echo "该类Sub已执行" ;
}
} echo "<h3>NewStatic的测试结果</h3>" ; $newStatic = new NewStatic(); echo "第一次执行初始化的结果:<br>" ; $newStatic -> init();
|
Copier après la connexion
remplacer static par self
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?phpclass NewStatic{
private $newStatic ;
public function init()
{
if ( empty ( $this -> newStatic)) { $this -> newStatic = new self();
echo "该类已初始化" ;
} else { $this -> newStatic -> exec ();
}
}
public function exec ()
{
echo "该类NewStatic已执行" ;
}
} class Sub extends NewStatic{
public function exec ()
{
echo "该类Sub已执行" ;
}
} echo "<h3>NewStatic的测试结果</h3>" ; $newStatic = new NewStatic(); echo "第一次执行初始化的结果:<br>" ; $newStatic -> init();
|
Copier après la connexion
Conclusion :
1 2 3 4 5 6 | 如果在子类中调用父类中含有 new static ()的方法时,它实例化子类,但是如果是父类中使用的是 new self()的话,那么实例化的就是父类了, new self()永远指向定义的那个类,而 new static ()
会绑定调用时的那个类(延迟绑定)这就是 new static ()和 new self()的区别。这个区别实际上跟 static ::和self::的区别是一样的,使用 static ::调用静态方法时调用的是延迟绑定后的类的静态方法,而self::指向定义的静态类的方法
另外要补充的一点 new self()等同于如下写法: $class = get_class();
或者 $class = __CLASS__ ; $obj = new $class (); new static ()等同于如下写法: $class = get_called_class(); $obj = new $class ();
或者 $class = get_class( $this );
|
Copier après la connexion
Recommandations associées :
Explication détaillée de la comparaison entre la liaison statique retardée et l'efficacité statique ordinaire en PHP
PHP Liaison tardive /delay liaison du parent et des sous-classes
Notes d'étude sur la programmation orientée objet PHP (oop) (2) - attributs et méthodes des variables statiques et liaison retardée_exemple php
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!