如何在不初始化类的情况下获得属性


How to get a property without initialize class?

我有一个问题,我的PHP代码,而试图获得一个数组。

我的代码

<?php
class Core{
    public $actions;
    public function __construct(){
        //set must be defined here
        $this->setter('this is the action');
    }
    public function returnAction(){
        // This method is just for testing purposes
        return $this->actions;
    }
    public function setter($actions){
        $this->actions = $actions;
    }
    public function getter(){
        return $this->actions;
    }
}
// If I try this, it throws an error, and of course it doesn't return the same as below:  Access to undeclared static property: Core::$actions 
echo Core::$actions;
// Same if I try this, I get this error: Using $this when not in object context
echo Core::returnAction();

// But if I do this, it works...
$class = new Core();
echo $class->actions;
事实上,由于显而易见的原因,

不起作用:在两种情况下都没有初始化class。我的问题是……在不初始化类的情况下,实现此代码运行的最佳方法是什么?

谢谢!

你正在调用一个非静态方法:

public function returnAction(){
    // This method is just for testing purposes
    return $this->actions;
}

但是你正在做一个静态调用:

echo Core::returnAction();

当你进行静态调用时,函数将被调用(即使不是静态的)。但是因为没有对象的实例,所以没有$this.

调用这个方法的正确方法如下:

$foo = new Core();
echo $foo->returnActions();

可以通过使用static关键字来访问公共属性或方法,而无需实例化类。

你会这样做:public static $actions; .

也就是说,你的类看起来确实像是被设计用来实例化的,因为它有构造函数、setter和getter。

我将简单地重写成这样:

class Core{
    public static $actions;
}

享受吧!

在@Melvin评论后更新