What is the difference between $this and self ?

What is the difference between $this and self ?

Inside a class definition, $this refers to the current object, while self refers to the current class.

It is necessary to refer to a class element using self ,
and refer to an object element using $this .
Note also how an object variable must be preceded by a keyword in its definition.

The following example illustrates a few cases:


<?php
class Classy {

const       STAT = 'S' ; // no dollar sign for constants (they are always static)
static     $stat = 'Static' ;
public     $publ = 'Public' ;
private    $priv = 'Private' ;
protected  $prot = 'Protected' ;

function __construct( ){  }

public function showMe( ){
    print '<br> self::STAT: '  .  self::STAT ; // refer to a (static) constant like this
    print '<br> self::$stat: ' . self::$stat ; // static variable
    print '<br>$this->stat: '  . $this->stat ; // legal, but not what you might think: empty result
    print '<br>$this->publ: '  . $this->publ ; // refer to an object variable like this
    print '<br>' ;
}
}
$me = new Classy( ) ;
$me->showMe( ) ;

/* Produces this output:
self::STAT: S
self::$stat: Static
$this->stat:
$this->publ: Public
*/
?>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容