PHP和静态类方法

时间:2014-03-04 16:44:25

标签: php class static static-methods

我正在寻找一个更好的理解静态方法如何在PHP中工作。我一直在阅读php手册网站上关于static keyword关于方法和类对象的文章,我很好奇。

让我说我有这个课程:

class Something{
    protected static $_something = null;

    public function __construct($options = null){
        if(self::$_something === null && $options != null){ 
            self::$_something = $options 
        }
    }

    public function get_something(){ return self::$_something }
}

所以你在index.php上实例化了这个,所以你做了类似的事情:

$class_instantiation = new Something(array('test' => 'example'));

很好,此时$_something包含key=>value数组,我们可以在同一页面上执行此操作:

var_dump($class_instantiation->get_something()); // var dumps the array we passed in.

BUT

如果我们现在创建sample.php并执行:

$class_instantiation = new Something();
var_dump($class_instantiation->get_something());

我们回复null(我假设你去了index.php,实例化了这个类并传入了数组,看到var_dump THEN 导航到{ {1}}。如果您在没有先前sample.php的情况下前往null,这将会返回sample.php,这是可以理解的。)

我假设静态方法“保存在类”的所有实例中,因此我应该能够使用或不使用传递给构造函数的对象来实例化类,假设某些东西是在那里取回我们在index.php

上创建的数组

所以我的问题是:

静态方法在类方面如何真正起作用?如果我只是传递物体,有没有办法做我正在尝试使用第三方工具?

2 个答案:

答案 0 :(得分:1)

PHP中的

static也意味着您可以在不实例化类的情况下访问property /方法。很难在同一个PHP执行中保留static变量,因为通常,执行将以服务器响应结束,但正如AbraCadaver所述,它们在同一个执行中按预期行事(同一请求,读取那样)

答案 1 :(得分:1)

在同一PHP执行中,静态属性为static。如果在index.php上运行它,那么在执行结束时它将被销毁。在sample.php,它将是一个新的执行。这可以按预期工作(执行相同):

//index.php
class Something{
    protected static $_something = null;

    public function __construct($options = null){
        if(self::$_something === null && $options != null){ 
            self::$_something = $options ;
        }
    }

    public function get_something(){ return self::$_something; }
}

$class_instantiation = new Something(array('test' => 'example'));
var_dump($class_instantiation->get_something());

$class_instantiation2 = new Something();
var_dump($class_instantiation2->get_something());

objects转储:

array(1) {
  ["test"]=>
  string(7) "example"
}