我只是想通过构造函数设置 post_id 并通过另一个函数获取该 id。但它正在返回: fatal error :不在对象上下文中时使用 $this
但不知道为什么会这样正在发生。我以前做过很多次,但现在出了问题。
代码如下
class PostData
{
private static $instance = null;
public $post_id = 0;
public function __construct($post_id = 0){
if((int)$post_id > 0){
$this->setId($post_id);
}
}
private function setId($post_id){
return $this->post_id = $post_id;
}
public static function getPostID(){
return $this->post_id;
}
public static function getInstance(){
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
我是如何称呼这个类(class)的
$post = new PostData(33);
echo $post->getPostID();
但是出现错误: fatal error :不在对象上下文中时使用 $this
最佳答案
您的问题是您在不允许的静态上下文中使用 $this
。根据定义,静态函数是无对象的,$this
引用一个对象。您需要将类重组为静态或非静态。
如何使用这个结构:
class PostData
{
public $post_id = 0;
public function __construct($post_id = 0){
if((int)$post_id > 0){
$this->setId($post_id);
}
}
private function setId($post_id){
return $this->post_id = $post_id;
}
public function getPostID(){
return $this->post_id;
}
}
根据 documentation :
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.
再次,根据关于如何调用静态属性的文档:
Static properties cannot be accessed through the object using the arrow operator ->.
Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static).
实例
关于php - fatal error : Using $this when not in object context - OOPHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50731551/