php的static关键字

Static Keyword

Tip

    This page describes the use of the static keyword to    define static methods and properties. static can also    be used to    define static variables    and for    late static bindings.    Please refer to those pages for information on those meanings of    static.  

   Declaring class properties or methods as static makes them accessible   without needing an instantiation of the class. A property declared as   static can not be accessed with an instantiated class object (though   a static method can). 

   For compatibility with PHP 4, if no visibility   declaration is used, then the property or method will be treated   as if it was declared as public

   Because static methods are callable without an instance of   the object created, the pseudo-variable $this is   not available inside the method declared as static. 

   Static properties cannot be accessed through the object using the arrow   operator ->. 

   Calling non-static methods statically generates an E_STRICT level warning. 

   Like any other PHP static variable, static properties may only be   initialized using a literal or constant; expressions are not   allowed. So while you may initialize a static property to an   integer or array (for instance), you may not initialize it to   another variable, to a function return value, or to an object. 

   As of PHP 5.3.0, it's possible to reference the class using a variable.   The variable's value can not be a keyword (e.g. self,   parent and static). 

Example #1 Static property example

<?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 . "\n";

$foo = new Foo();
print
$foo->staticValue() . "\n";
print
$foo->my_static . "\n";      // Undefined "Property" my_static

print $foo::$my_static . "\n";
$classname = 'Foo';
print
$classname::$my_static . "\n"; // As of PHP 5.3.0

print Bar::$my_static . "\n";
$bar = new Bar();
print
$bar->fooStatic() . "\n";
?>

Example #2 Static method example

<?php
class Foo {
    public static function
aStaticMethod() {
       
// ...
   
}
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值