且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不在对象上下文中时使用$ this-Laravel 4 PHP 5.4.12

更新时间:2023-11-15 07:56:52

使用静态方法时,不能使用$this.静态方法不知道对象状态.您只能使用self::引用静态属性和对象.如果要使用对象本身,则需要感觉自己不在类之列,因此需要创建一个对象的实例,但这将无法理解对象中之前发生的事情. IE.如果某些方法将属性$_x更改为某个值,则在重新实例化该对象时,将失去该值.

You cannot use $this when you are in static method. Static methods are not aware of the object state. You can only refer to static properties and objects using self::. If you want to use the object itself, you need to feel like you are out of the class, so you need to make instance of one, but this will fail to understand what has happened before in the object. I.e. if some method changed property $_x to some value, when you reinstance the object, you will lose this value.

但是,您可以这样做

$_this = new self;
$_this->event->create($info);

您也可以将非静态方法称为静态self::method(),但是在较新版本的PHP中,您会收到错误消息,因此***不要这样做.

You can also call non static methods as static self::method() but in newer versions of PHP you will get errors for this, so it's better to not do it.

有关此信息,您可以在官方php文档中找到: http://www .php.net/manual/en/language.oop5.static.php

The information about it, you can find in the official php documentation: http://www.php.net/manual/en/language.oop5.static.php

因为静态方法可以在没有对象实例的情况下被调用 创建后,伪变量$ this在方法内部不可用 声明为静态

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static


静态调用非静态方法会生成E_STRICT级别 警告.

Calling non-static methods statically generates an E_STRICT level warning.