您需要在class 属性中声明global 做什么?我们在这里处理的不是普通的functions。 $this->var1 将从类内的任何method 或从类外的实例化对象(变量为public)中获取$var1。 但让我们彻底...
说明“全球”
全局对于类属性没有意义;尽管您可以将它与类方法中的变量一起使用,就像您可以使用常规函数一样。 (但有更优雅的方法可以实现;最好避免在全局范围内产生潜在危险的混乱。)让我们首先定义一个变量:
$globby = 123; // Globby is a friend living outside a function.
不使用global 声明的函数既不能从其范围之外访问变量,也不能更改该变量的值。故事是这样的:
function foo() {
echo $globby; // Here we have no clue who globby is?
$globby = 321; // Here we define globby, but then he's totally forgotten. :(
}
foo(); // => 'Notice: Undefined variable: globby'
echo $globby; // => '123' ... still the same old globby.
但是,将变量声明为global 的函数既可以访问它,也可以在函数范围之外修改它。此外,在函数内部新定义为全局的变量可以在函数外部访问。
function foot() {
global $globby; // Hey globby, won't you come on in! *Globby UFO Lands*
echo $globby; // - Who are you? - I'm globby that says 123.
$globby = 321; // - But I'm gonna tell you to say 321 everywhere.
}
foot(); // => '123' ... this here is the good old globby from the start.
echo $globby; // => '321' ... see, globby can change outside the function scope!
说明类中的“静态”
请注意,类属性的static不像函数变量的static那样工作。手册:“静态变量仅存在于局部函数范围内,但当程序执行离开此范围时,它不会失去其值。”再次:“将类属性或方法声明为静态使它们无需实例化类即可访问。”(OOP Static Keyword; 和 Using Static Variables)在任何情况下,类属性在对象的生命周期内都保留其值。
现在,来说明静态和非静态方法(又名“类函数”)和属性(又名“类变量”)的用法(和非用法)。让我们开一个小班:
class foo {
static $one = 1; // This is a static variable aka. class property.
var $two = 2; // But this is non-static.
static function say_one() { // This is a static method.
echo self::$one; // Uses self:: to statically access the property.
}
function say_two() { // This is a non-static method.
echo $this->two; // Uses $this-> to dynamically access the property.
}
}
那么让我们看看哪些有效,哪些无效。不可用的选项被注释掉。
/* Static Variables and Methods */
echo foo::$one; // => '1'
echo foo::say_one(); // => '1'
// echo foo::$two;
// => "Fatal error: Access to undeclared static property: foo::$two"
// echo foo::say_two();
// => "Strict: Non-static method foo::say_two() should not be called statically.
// & Fatal error: Using $this when not in object context."
/* Non-Static Variables and Methods */
$f = new foo(); // This here is a real effin' instantiated dynamite object. *BOOM*
echo $f->two; // => '2'
echo $f->say_two(); // => '2'
// echo $f->one;
// => "Strict: Accessing static property foo::$one as non static.
// & Notice: Undefined property: foo::$one."
echo $f->say_one(); // => '1'
希望澄清。请注意,您可以通过实例化对象访问静态方法,并使用它来访问静态变量;但是您不能在没有警告的情况下直接访问静态变量作为非静态变量。
让我添加一个关于良好做法的说明。如果您发现需要在函数中重复声明 global 变量,或将配置参数等作为函数参数传递,则表明您可能应该将代码分解为类,将这些全局变量作为其属性访问. OOP 使用起来非常干净。你会更快乐地编码。 $OOP->nirvana();.