打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
PHP的静态方法介绍

静态方法的规则和静态变量是相同的。使用ststic关键字可以将方法标识为静态方法,通过类的名称和作用域限定操作符::可以访问静态方法。

静态方法和非静态方法之间有一个很重要的区别,就是在调用静态方法时,我们不需要创建类的实例。

Program List:用类名作为参数

用类名作为参数可以解决非继承的静态问题。

01<?php
02class Fruit {
03    public static $category "I'm fruit";
04     
05    static function find($class)
06    {
07        $vars = get_class_vars($class) ;
08        echo $vars['category'] ;
09    }
10}
11 
12class Apple extends Fruit {
13     public static $category "I'm Apple";
14}
15 
16Apple::find("Apple");
17?>

程序运行结果:

1I'm Apple

Program List:重写基类方法

在派生类重写基类的方法。

01<?php
02class Fruit
03{
04    static function Foo ( $class __CLASS__ )
05    {
06        call_user_func(array($class'Color'));
07    }
08}
09 
10class Apple extends Fruit
11{
12    static function Foo ( $class __CLASS__ )
13    {
14        parent::Foo($class);
15    }
16 
17    static function Color()
18    {
19        echo "Apple's color is red";
20    }
21}
22 
23Apple::Foo(); // This time it works.
24?>

程序运行结果:

1Apple's color is red

Program List:静态数组的使用

静态和const作用域都可以用::操作符访问,如果你想使用::操作符访问数组,你需要事先将数组声明为静态。

01<?php
02class Fruit
03{
04    static $color array('color1' => 'red''color2' => 'yellow');
05}
06 
07class Apple
08{
09    public function __construct()
10    {
11        var_dump(Fruit::$color);
12    }
13}
14 
15class Banana
16{
17  public function __construct()
18  {
19    Fruit::$color = FALSE;
20  }
21}
22 
23new Apple();    // prints array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" }
24echo '<br />';
25new Banana();
26new Apple();    // prints bool(false)
27?>

程序运行结果:

1array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" }
2bool(false)

Program List:再来一个单例模式

Static真的很酷,下面的程序演示了如何获得一个已经存在的实例。

01<?php
02class Singleton {
03 
04    private static $instance=null;
05    private $value=null;
06 
07    private function __construct($value) {
08        $this->value = $value;
09    }
10 
11    public static function getInstance() {
12        if ( self::$instance == null ) {
13            echo "<br>new<br>";
14            self::$instance new Singleton("values");
15        
16        else {
17            echo "<br>old<br>";
18        }
19        return self::$instance;
20    }
21 
22}
23 
24$x = Singleton::getInstance();
25var_dump($x); // returns the new object
26$y = Singleton::getInstance();
27var_dump($y); // returns the existing object
28?>

程序运行结果:

1new
2object(Singleton)#1 (1) { ["value:private"]=> string(6) "values" }
3old
4object(Singleton)#1 (1) { ["value:private"]=> string(6) "values" }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
vc静态变量构造析构顺序
C#(九)基础篇—静态成员与异常处理
C++ 线程安全的单例模式
java几种方式实现单例设计模式
聊聊 Python 面试最常被问到的几种设计模式(上)
博客园 - 探索设计模式(二):深入浅出单件模式(Sigleton Pattern)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服