我什么时候应该使用 'self' 而不是 '$this'?

编程入门 行业动态 更新时间:2024-10-09 23:12:18
本文介绍了我什么时候应该使用 'self' 而不是 '$this'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

In PHP 5, what is the difference between using self and $this?

When is each appropriate?

解决方案

Short Answer

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

Full Answer

Here is an example of correct usage of $this and self for non-static and static member variables:

<?php class X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo $this->non_static_member . ' ' . self::$static_member; } } new X(); ?>

Here is an example of incorrect usage of $this and self for non-static and static member variables:

<?php class X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo self::$non_static_member . ' ' . $this->static_member; } } new X(); ?>

Here is an example of polymorphism with $this for member functions:

<?php class X { function foo() { echo 'X::foo()'; } function bar() { $this->foo(); } } class Y extends X { function foo() { echo 'Y::foo()'; } } $x = new Y(); $x->bar(); ?>

Here is an example of suppressing polymorphic behaviour by using self for member functions:

<?php class X { function foo() { echo 'X::foo()'; } function bar() { self::foo(); } } class Y extends X { function foo() { echo 'Y::foo()'; } } $x = new Y(); $x->bar(); ?>

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

From www.phpbuilder/board/showthread.php?t=10354489:

By board.phpbuilder/member.php?145249-laserlight

更多推荐

我什么时候应该使用 'self' 而不是 '$this'?

本文发布于:2023-11-29 04:17:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   而不是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!