PHP:有多少行不起作用,静态访问与非静态访问
http://codepad.viper-7.com/ezvlkQ
所以,我想弄清楚out:
...?php
$object = new A();
class A
{
static public $foo = 'bar';
function displayFoo()
{
echo $this->$foo;
}
}
A::displayFoo();
A->displayFoo();
?>
关于这个,你能发现多少错误?你能告诉我它们在真正的人类术语中是什么吗?我无法真正从键盘使用的验证器中解释什么是可以的,什么是不行的......
http://codepad.viper-7.com/ezvlkQ
So, I'm trying to figure out:
...?php
$object = new A();
class A
{
static public $foo = 'bar';
function displayFoo()
{
echo $this->$foo;
}
}
A::displayFoo();
A->displayFoo();
?>
About this, how many errors can you find? Can you tell me what they are in real human terms? I can't really interpret what is and what is not okay from the validator that codepad uses...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我已在此处更新了您的代码 http://codepad.viper-7.com/UaUE4g
错误1:
这应该是:
..因为它是静态的。
错误2:
该方法是一个实例方法
::
用于访问静态方法。错误 3:
这是一个错误,因为
A
未定义,如果是,则应该读取$A
。这没问题:.. 因为 $object 是类 A 的一个实例。
下一步,请查阅关于静态主题的手册。
I’ve updated your code here http://codepad.viper-7.com/UaUE4g
Error 1:
This should read:
.. as it is static.
Error 2:
The method is an instance method
::
is used for access to static methods.Error 3:
This is an error because
A
is undefined and if it was it should have read$A
. This would be okay:.. as $object is an instance of class A.
Next step, consult the manual on the topic static.
不知道从哪里开始。静态方法属于类,普通方法属于对象,即该类的实例化。例如,您可以:
这之所以有效,是因为您正在调用属于类
A
的displayFoo
方法。或者您可以这样做:现在您正在基于
A
类创建一个对象。该对象可以调用它的方法。但对象没有静态方法。如果您将函数声明为静态,则$obj
将无法使用该函数。你不能这样做:
在任何情况下,在任何情况下,永远都不能这样做。
->
运算符假定一个对象,而A
不能是对象,因为它不是变量。Not sure where to start. Static methods belong to the class, normal methods belong to an object, an instantiation of that class. For example, you can have:
This works because you're calling the
displayFoo
method belonging to classA
. Or you can do this:Now you're creating an object based on the class of
A
. That object can call its methods. But the object doesn't have static methods. If you were to declare the function static, it would not be available to$obj
.You can't do:
at all, under any circumstances, ever. The
->
operator assumes an object, andA
can't be an object because its not a variable.您可以在此处阅读手册中的静态类成员:
http://php.net/static
密切关注到例子。
You can read up on static class members in the manual here:
http://php.net/static
Pay close attention to the examples.