严格标准部分是因为a::read() 是在静态上下文中使用:: 调用的。在将$a 声明为A 的类实例之后,您应该使用-> 运算符对变量调用read() 方法:
// Proper non-static method call
$a = new A();
$a->read();
在类定义中,$foo 被声明为私有属性,但没有 static 关键字。然后在静态上下文中使用:: 运算符而不是-> 来引用它。访问它的正确方法是L
// Proper reference to non-static $foo
function read() {
echo $this->foo;
}
现在static 到底是什么意思?静态方法和属性是指所有当前和未来类实例共享的类方法和属性。如果A::$foo 被声明为:
private static $foo;
那么您的代码中将只有一个 $foo 用于所有类 A。更改$foo 会影响A 类的所有实例,并且$foo 甚至可以在不创建该类的实例的情况下被访问(如new A();)
同样,静态方法可以在不创建类实例的情况下调用,因为它们不会修改非静态的类属性。
// Static method call:
A::read();
要将属性和方法声明为static,只需添加static 关键字:
// Property
private static $foo;
// Method
public static function foo() {}
编辑更多示例:
class A
{
// Private property (non-static)
private $foo;
// Public property (static)
public static $bar = 12345;
// Public (non-static) function to access private $foo
public function getFoo() { return $this->foo; }
// Public (non-static) function to set private $foo
public function setFoo($newfoo) { $this->foo = $newfoo; }
// Static function
public static function incrementBar() { self::$bar++; }
}
现在看看它的实际效果:
// We haven't created any class instances yet (with the 'new' operator)
// But we can access the static properties & functions:
echo A::$bar . " ";
// prints 12345
A::incrementBar();
echo A::$bar . "\n";
// prints 12346
// Now we'll start working with class instances.
// Create 2 instances of class A
$a = new A();
$a->setFoo(8888);
$b = new A();
$b->setFoo(9999);
// It's a violation of strict standards to call getFoo() statically
// And it's meaningless to do so, because $foo only exists inside a class instance!
// Can't do this... Issues a strict warning since we're calling non-static getFoo() statically
//echo A::getFoo();
// But we can call getFoo() on the class instances:
echo $a->getFoo() . " " . $b->getFoo() . "\n";
// Prints 8888 9999
// Remember $bar was 12346...
echo $a::$bar . " " . $b::$bar . "\n";
// Prints 12346 12346
// Now modify the static property $bar again
// This affects all class instances.
A::incrementBar();
echo $a::$bar . " " . $b::$bar . "\n";
// Prints 12347 12347
我也把整个东西都塞进了键盘:http://codepad.viper-7.com/tV6omK
您正在阅读的书一定没有遵循严格的标准。如果非静态函数不尝试访问/修改非静态属性,您可以成功地静态调用它,但它会发出严格的警告。如果非静态函数使用$this->property 修改或访问非静态属性,这将是一个致命错误。你不能那样做。
在 PHP 的error_reporting 中,E_ALL 显示所有错误的设置实际上不包括严格的警告。这必须通过E_ALL & E_STRICT 完成。