【发布时间】:2014-05-22 13:15:41
【问题描述】:
我有一个名为testclass 的类和其中的几个函数。他们都需要访问一个预定义变量$need_to_have。我想在类中定义它,但是如何定义呢?
例子:
class testclass {
// This won't work:
private static $need_to_have = get_some_info();
public static testfunction1() {
// Do Something with $need_to_have
}
public testfunction2 () {
// Do something else with $need_to_have
}
}
忘了说:我想把它私有化,而且我只在静态函数上调用变量,所以我不能使用构造函数。
【问题讨论】:
-
将其声明为公开的......但要注意它很容易从您的对象外部发生意外更改。我最好创建一个公共 getter 方法。
-
不,我定义它的地方用于类常量,并且只允许使用像
true、"String"和5这样的简单值。不允许在其中调用函数甚至其他变量。 -
@Brainiac 那么你对仅仅设置访问级别有什么担心
-
@RoyalBg 你所说的“制定访问级别”是什么意思?
-
testclass::getNeedToHave()你有 public staticgetNeedToHave()getter