首页 > php代码 > php Static关键字静态变量的实用方法(1/3)

php Static关键字静态变量的实用方法(1/3)

<?php
class Foo {
    public static $my_static = 'foo';
    public function staticValue() {
        return self::$my_static;
    }
}
class Bar extends Foo {
    public function fooStatic() {
        return parent::$my_static;
    }
}
print Foo::$my_static . " ";
$foo = new Foo();
print $foo->staticValue() . " ";
print $foo->my_static . " "; // Undefined "Property" my_static
print $foo::$my_static . " ";
$classname = 'Foo';
print $classname::$my_static . " "; // PHP 5.3.0之后可以动态调用
print Bar::$my_static . " ";
$bar = new Bar();
print $bar->fooStatic() . " ";
?>

 

 

静态方法的引用方法

<?php
/*
 *author:ajax123
 *qq:283400245
*/
class person {
    static $name = "ajax123"; //static声明静态属性
    static $age = 25; //static声明静态属性
    static $address = "北京"; //static声明静态属性
    function song() {
        echo "My name is : " . self::$name . "<br>"; //类内部:通过通过self 类访问静态属性
        echo "I am " . self::$age . "<br>"; //类内部:通过通过self 类访问静态属性
        echo "I live in " . self::$address . "<br>"; //类内部:通过self 类访问静态属性
        
    }
}
echoperson::$name . "<br>"; //类外部:通过类名person访问静态属性
echoperson::$age . "<br>"; //类外部:通过类名person访问静态属性
echoperson::$address . "<br>"; //类外部:通过类名person访问静态属性
?>


<?php
/*
 *author:ajax123
 *qq:283400245
*/
class person {
    static $name = "ajax123"; //static声明静态属性
    static $age = 25; //static声明静态属性
    static $address = "北京"; //static声明静态属性
    static function song() { //声明静态方法song
        echo "My name is : " . self::$name . "<br>"; //类内部:通过通过self 类访问静态属性
        echo "I am " . self::$age . "<br>"; //类内部:通过通过self 类访问静态属性
        echo "I live in " . self::$address . "<br>"; //类内部:通过self 类访问静态属性
        
    }
}
person::song() . "<br>"; //类外部:通过类名person访问静态方法
?>


本文地址:http://www.phprm.com/code/33303.html

转载随意,但请附上文章地址:-)

标签:none

发表留言