Home  >  Article  >  Backend Development  >  php self

php self

WBOY
WBOYOriginal
2016-08-08 09:23:001277browse
php类中的this,self,parent

this代表当前对象,self代表当前类,parent代表父类,这个解释很晦涩,下面结合例子具体说明一下self

php类的定义和对象(实例)的存储是分开的,类的定义只有一份,实例可以有多个。self就代表类定义

类的定义主要包括方法(类的属性可以动态添加),不严谨的说,方法是属于类的,属性是属于对象的。

那么理论上通过类名就可以调用类的所有方法(包括静态,非静态,注意访问限制),包括继承来的,从这个角度来说self==当前类。

所以
通过self,类名可以调用本类的常规方法,静态方法,父类的方法(后记,如方法中用了this,会报运行时错误,但语法没有问题)
rrree
<pre name="code" class="php">class A
{
    public static $count=1;
    const N = 10; 
    private $_a = "_a \n";
    protected $_b = "_b \n";
    public $c = "c \n";

    public function n() {
        echo  __METHOD__."\n";
    }   

    public function func() {
        echo  __METHOD__." " .$this->c;
    }   

    public static function f() {
        echo  __METHOD__."\n";
    }   

    public static function fn() {
        echo __METHOD__." " .self::N."\n";
    }   
}

class B extends A
{
    const N = 100;

    public static $count=1;
    public $p = "pp\n";

    public function d() {
        echo __METHOD__." ".$this->p." \n";
    }   

    public  function e() {
        self::n();
        echo __METHOD__." \n";
    }

    public static function f(){
        self::e();
        self::n();
        echo __METHOD__."\n";
    }

    public function func() {
        parent::func();
        echo "func\n";
    }
}

echo "=========B:e()=========\n";
B::e();

echo "=========B:n()=========\n";
B::n();

echo "=========B:f()=========\n";
B::f();

echo "=========B:d()=========\n";
B::d(); // 运行时错误error

The above has introduced php self, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:a filter functionNext article:a filter function