【发布时间】:2016-03-26 18:50:13
【问题描述】:
我正在尝试在另一个类中调用类方法。
<?php
class A {
public static $instant = null;
public static $myvariable = false;
private function __construct() {}
public static function initial() {
if (static::$instant === null) {
$self = __CLASS__;
static::$instant = new $self;
}
return static::$instant; // A instance
}
}
class B {
private $a;
function __construct($a_instance) {
$this->a = $a_instance;
}
public function b_handle() {
// should be:
$this->a::$myvariable = true;
// but:
// Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
// try with:
// $this->a->myvariable = true;
// but:
// Strict Standards: Accessing static property A::$myvariable as non static
}
}
// in file.php
$b = new B(A::initial());
$b->b_handle();
var_dump(A::$myvariable);
目前,我的替代方案是:
<?php
class A {
public function set_static($var,$val) {
static::$$var = $val;
}
}
所以:
$this->a->set_static('myvariable',true);
我该怎么办? 发生了什么? 我错了吗?
为什么我不能直接从 B 类将 myvariable 设置为静态变量?
抱歉英语不好。
【问题讨论】:
-
这是非常不寻常的代码,我认为这里有几个问题让您和其他可能的回答者感到困惑。尝试将其放入
B的__construct()方法中,您会立即看到以下几个问题之一:var_dump($a_instance);我得到了NULL打印出来,因此您的代码没有按照您的想法执行。 -
$myvariable是一个静态属性。使用classname::语法分配。 -
和
static::$instant !== null- 所以如果它是 NOT null 你创建一个新的。如果它是空的,你只返回空?你确定吗? -
哦,抱歉 A::initial() 中的代码错误,应该是 if (static::$instant === null)
-
@u_mulder ,我做到了。来自 A::initial() 的瞬间
标签: php class methods static singleton