PHP面向对象——this self parent总结

这里只是简单总结,这三个关键字和静态方法密切相关

this指向对象

详见静态调用不进行this绑定

  • 静态调用类中所有类型的方法都不需要绑定this
  • 静态方法中本身就不能有this,自然不存在绑定this
  • 对象调用类中的静态方法,不需要绑定this,因为,静态方法不属于哪个对象
  • 对象调用类中的非静态方法时,该方法执行之前先完成一个绑定, this绑定到调用此方法的对象
  • 静态调用非静态方法是不推荐的,但在继承中常用来访问父类方法,如parent::__construct()
class A{
    public function foo(){
        if (isset($this)){
            echo 'this is defined~',get_class($this),"\n";
        }else{
            echo 'this is not defined',"\n";
        }
    }
}

class B{
    public function bar(){	// $b->bar()  $b绑定B类中的$this   并没有绑定A类中的$this
        A::foo();   // 静态调用不执行this绑定   用类名调用即静态调用
    }
}


$a = new A();
$a->foo();   // foo()是非静态方法,$a绑定到$this,因此 this is defined~A
A::foo();    // 静态调用 未绑定$this  this is not defined

$b = new B();
$b->bar();   // bar()是非静态方法,$b绑定到$this, bar(){B::foo()-这里是静态调用,不操作$this},因此this is defined~B
B::bar();    // 静态调用 未绑定$this  this is not defined

self指向本类

详见静态调用不进行this绑定

  • 其实就是在类内静态访问时用self代替本类自己
  • 这样代替的意义是,如某些原因改了类名,self就不用改了
class Human{
    static public $head = 1;

    public function show(){
        // 这里self::$head等同于Human::$head  但用self更合理,如果改了类名这里就不用改了
        echo self::$head,'<br>';
    }
}

echo Human::$head,'<br>';

$lisi = new Human();
$lisi->show();

parent指向父类

详见静态调用不进行this绑定

  • 其实就是在类内静态访问父类时用parent代替父类名
  • 静态调用非静态方法是不推荐的,但在继承中常用来访问父类方法,如parent::__construct()
class A{
    public function foo(){
        if (isset($this)){
            echo 'this is defined~',get_class($this),"\n";
        }else{
            echo 'this is not defined',"\n";
        }
    }

}


class B extends A{
    public function bar(){
        parent::foo();
    }
}

$b = new B();
$b->bar();  // bar()是非静态方法,$b绑定了bar()方法中的$this, bar(){parent::foo()-这里是静态调用,不操作$this},因此this is defined~B
B::bar();   // 静态调用 未绑定$this  this is not defined
B::foo();   // 静态调用 未绑定$this  this is not defined
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值