PHP中new self()与new static()有何本质区别?

更新于
2026-09-30 11:01:43
1阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计506个文字,预计阅读时间需要3分钟。

PHP中new self()与new static()有何本质区别?

PHP中`new self()`和`new static()`的区别:

`new self()`和`new static()`都是PHP 5.3版本引入的新特性。它们都用于创建一个对象实例,但它们的区别在于使用场景和作用域。

PHP中new self()与new static()有何本质区别?

- `new self()`:用于在同一个类内部创建当前类的对象实例。它等价于`new $this`。

- `new static()`:用于在同一个类内部创建当前类的静态对象实例。这意味着无论当前对象是实例化的还是静态的,`new static()`都会创建一个静态对象。

以下是一个简单的例子:

phpclass Father { public function getNewFather() { return new self(); }

public function getNewStatic() { return new static(); }}

在这个例子中,`getNewFather()`方法返回当前类的对象实例,而`getNewStatic()`方法返回当前类的静态对象实例。

PHP中new self() 和 new static() 的区别

new static() 是在php5.3版本引入的新特性

new static 和 new self() 都是 new 一个对象

直接看代码

class Father { public function getNewFather() { return new self(); } public function getNewCaller() { return new static(); } } $f = new Father(); var_dump(get_class($f->getNewFather())); // Father var_dump(get_class($f->getNewCaller())); // Father

getNewFather和getNewCaller 都是返回的 Father 这个实列

到这里貌似 new self() 还是 new static() 是没有区别的

接着看下面的示例

class Sun1 extends Father{ } $sun1 = new Sun1(); var_dump($sun1->getNewFather()); // object(Father)#4 (0) { } var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { }

getNewFather 返回的是Father的实列,

getNewCaller 返回的是调用者的实列

他们的区别只有在继承中才能体现出来、如果没有任何继承、那么二者没有任何区别

new self() 返回的实列是不会变的,无论谁去调用,都返回的一个类的实列,

new static则是由调用者决定的。

推荐教程:《PHP视频教程》

以上就是区别PHP中new self() 和 new static()的详细内容,更多请关注自由互联其它相关文章!

本文共计506个文字,预计阅读时间需要3分钟。

PHP中new self()与new static()有何本质区别?

PHP中`new self()`和`new static()`的区别:

`new self()`和`new static()`都是PHP 5.3版本引入的新特性。它们都用于创建一个对象实例,但它们的区别在于使用场景和作用域。

PHP中new self()与new static()有何本质区别?

- `new self()`:用于在同一个类内部创建当前类的对象实例。它等价于`new $this`。

- `new static()`:用于在同一个类内部创建当前类的静态对象实例。这意味着无论当前对象是实例化的还是静态的,`new static()`都会创建一个静态对象。

以下是一个简单的例子:

phpclass Father { public function getNewFather() { return new self(); }

public function getNewStatic() { return new static(); }}

在这个例子中,`getNewFather()`方法返回当前类的对象实例,而`getNewStatic()`方法返回当前类的静态对象实例。

PHP中new self() 和 new static() 的区别

new static() 是在php5.3版本引入的新特性

new static 和 new self() 都是 new 一个对象

直接看代码

class Father { public function getNewFather() { return new self(); } public function getNewCaller() { return new static(); } } $f = new Father(); var_dump(get_class($f->getNewFather())); // Father var_dump(get_class($f->getNewCaller())); // Father

getNewFather和getNewCaller 都是返回的 Father 这个实列

到这里貌似 new self() 还是 new static() 是没有区别的

接着看下面的示例

class Sun1 extends Father{ } $sun1 = new Sun1(); var_dump($sun1->getNewFather()); // object(Father)#4 (0) { } var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { }

getNewFather 返回的是Father的实列,

getNewCaller 返回的是调用者的实列

他们的区别只有在继承中才能体现出来、如果没有任何继承、那么二者没有任何区别

new self() 返回的实列是不会变的,无论谁去调用,都返回的一个类的实列,

new static则是由调用者决定的。

推荐教程:《PHP视频教程》

以上就是区别PHP中new self() 和 new static()的详细内容,更多请关注自由互联其它相关文章!