标签:
this 绑定的是当前已经实例化的对象
这样长出现的问题: 如果你在一个父类中使用$this调用当前一个类的方法或者属性,如果这个类被继承,且在相应的子类中有调用的属性或者方法是,则父类中的$this调用的方法或者属性会使用子类中的方法。
<?php class baseParent { static $counter = 0; function getName() { return ‘baseParent‘; } function printName() { echo $this->getName() . "\n"; } } class base extends baseParent { static $counter = 0; function addCounter() { return self::$counter +=1; } function getName() { return ‘base‘; } } $one = new base(); $one->printName();
输出: base
parent 指向当前对象的父类的
self 指向当前类本身的,不指向任何已经实例化的对象的,一般用于指向类中的静态变量和静态方法: 因为静态方法和静态的变量是不能实例化到对象当中的,它只存在于当前类中
<?php class baseParent { static $counter = 0; } class base extends baseParent { function addCounter() { return self::$counter +=1; } } $one = new base(); echo $one->addCounter() . "\n"; $two = new base(); echo $two->addCounter() . "\n"; echo baseParent::$counter;
输出:1 2 2
static 后期静态绑定:
static::不再被解析为定义当前方法所在的类,而是在实际运行时计算的。也可以称之为"静态绑定",
因为它可以用于(但不限于)静态方法的调用。
<?php class baseParent { static $counter = 0; function getName() { return ‘baseParent‘; } function printName() { echo static::getName() . "\n"; } } class base extends baseParent { static $counter = 0; function addCounter() { return self::$counter +=1; } function getName() { return ‘base‘; } } $one = new base(); $one->printName();
输出: base
PHP 之 this self parent static 对比
标签:
原文地址:http://www.cnblogs.com/axwing/p/4272056.html