php学习之旅:static变量与方法

来源:互联网 发布:yy神曲下载软件 编辑:程序博客网 时间:2024/05/16 09:48

static关键字用来修饰属性、方法,称这些属性、方法为静态属性、静态方法。

static的方法,只能访问static的属性,不能类访问非静态的属性。不过调用非静态方法不可以使用this关键字调用非静态方法,而必须使用self::关键字,并且被调用的非静态方法中不能有非静态变量,一般情况静态方法尽量不要调用非静态方法

static的属性,在内存中只有一份,为所有的实例共用。

可以使用self:: 关键字访问当前类的静态成员。

非静态方法调用静态变量

<?php    class test{        public static $pi=3.14;        function display()        {            return self::$pi;        }       }    $test=new test();    echo '<br/>'.$test->display();?>

静态方法调用静态变量

<?php    class test{        public static $pi=3.14;        static function display_static()        {            return self::$pi;        }       }    $test=new test();    echo '<br/>'.$test::display_static();?>

非静态方法调用静态方法

<?php    class test{        public static $pi=3.14;        static function display_static()        {            return self::$pi;        }           function display()        {            return self::display_static();        }    }    $test=new test();    echo '<br/>'.$test->display();?>

静态方法调用非静态方法(实际就相当于将非静态方法在调用过程中转变为静态方法来处理了)

<?php    class test{        public static $pi=3.14;        static function display_static()        {            return self::display();        }           function display()        {            return self::$pi;        }    }    $test=new test();    echo '<br/>'.$test::display_static();?>
1 0
原创粉丝点击