面向对象的 静态属性,静态方法 static 详解

来源:互联网 发布:ubuntu 32位兼容库 编辑:程序博客网 时间:2024/05/18 02:00
class Human {    static public $head = 1;    public function changeHead() {        Human::$head = 9;    }    public function getHead() {        return Human::$head;    }}
静态属性:

// 现在没有对象,想访问静态的$head属性
普通属性包在对象内,用对象->属性名 来访问
静态属性放在类内的,

静态属性既然存放于类空间内

1:类声明完毕,该属性就已存在,不需要依赖于对象而访问

2:类在内存中只有一个,因此静态属性也只有一个

/ 当一个对象都没有,静态属性也已随类声明而存//

静态属性只有一个,为所有的对象的共享.


静态方法:


普通方法,存放于类内的,只有1份
静态方法,也是存放于类内的,只有1份


区别在于: 普通方法需要对象去调动, 需要绑定$this
即,普通方法,必须要有对象,用对象调动


而静态方法, 不属性哪个对象,属于类,因此不需要去绑定$this,
即, 静态方法,通过类名就可以调动


class Human {    public $name = '张三';    static public function cry() {        echo '5555';    }    public function eat() {        echo '吃饭';    }    public function intro() {        echo $this->name;    }}// 此时一个对象都没有Human::cry();


总结

如上分析,其实非静态方法,是不能由类名静态调用的.
但是! PHP中的面向对象检测的并不严格,
只要该方法没有$this,就会转化静态方法来调用.
因此,cry()可以调用.


但是,在PHP5.3的strict级别下,或者PHP5.4的默认级别
都已经对类名::非静态方法做了提示


则会提示:Strict Standards: Non-static method Human::eat() should not be called statically
不能静态的去调用非静态方法


类->访问->静态方法 可以
类->动态方法  方法内没有this的情况下,但严重不支持.逻辑上解释不通.

对象-->访问动态方法  可以
对象-->静态方法     可以

经典例子:

class A{function foo(){if (isset($this)) {echo '$this is defined (';echo get_class($this);echo ")\n";} else {echo "\$this is not defined.\n";}}}class B{function bar(){A::foo();}}$a = new A();$a->foo();    //(1)A::foo();     //(2)$b = new B();  //(3)$b->bar();   //(4)             B::bar();    

(1): $a是一个对象 因此绑定了$this 所以$this 存在 ‘$this is defined (a)’ 

(2):A::foo() 没有对象  因此没有绑定$this 所以 $this 不存在 ‘’$this is not defined''

(3)$b 是一个类B的对象  调用bar方法时  A::foo 静态调用foo 但是这个静态调用 不会绑定$this 而$b开始的时候绑定了 $this 所以$this 不会变 结果是‘$this is defined (b)’

(4)$this is not defined


$a = new A();
$a->foo();   // foo是普通方法,$a绑定到$this,因此,$this is defined(A);
A::foo();    // 这样调用,是不规范的.$this is not defined

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






原创粉丝点击