使用 PHP 对象访问静态属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17107869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:16:36  来源:igfitidea点击:

Access Static properties using PHP object

phpstatic

提问by user2314576

This is with reference to Get a static property of an instance, I am a newbie and have the following code :

这是参考获取实例的静态属性,我是新手并且有以下代码:

class Foo
{
   public static $my_static = 1;
}

class Bar extends Foo
{

}

$foo = new Foo();
$boo = new Bar();

echo Foo::$my_static;  // ok
echo Bar::$my_static;  // ok
echo $foo::$my_static; // ok
echo $boo::$my_static; // ok

Static variables/properties are accessed only as ClassName::static_propertyas in C++, but it is not the case in PHP... but PHP books mostly mention the className::static_propertypattern, not the object::static_propertyconstruct. Need more light on this..

静态变量/属性仅作为ClassName::static_property访问,就像在 C++ 中一样,但在 PHP 中并非如此……但 PHP 书籍大多提到className::static_property模式,而不是object::static_property构造。需要更多的了解这个..

回答by Robert

Static properties may be accessed on various ways.

可以通过多种方式访问​​静态属性。

Class::$aStaticProp; //by class name

$classname::$aStaticProp; // As of PHP 5.3.0 by object instance

Static properties cannot be accessed through the object using the arrow operator ->.

无法使用箭头运算符通过对象访问静态属性->

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

从 PHP 5.3.0 开始,可以使用变量来引用类。变量的值不能是关键字(例如 self、parent 和 static)。

More you can read in manual

您可以在手册中阅读更多内容

回答by deceze

$instance::$staticPropertyis simply a convenience shorthand for Class::$staticProperty. Since you already have an instance of a classand the syntax is unambiguous, PHP saves you from writing a potentially long class name. There's no functional difference.

$instance::$staticProperty只是 的方便简写Class::$staticProperty。由于您已经有一个的实例并且语法是明确的,PHP 使您无需编写可能很长的类名。没有功能上的区别。

回答by Alp Altunel

within the class you have to use like self::$staticPropery if the function accessing to the variable is also static.

在类中,如果访问变量的函数也是静态的,则必须像 self::$staticPropery 一样使用。