如何在没有初始化类的情况下获取属性?

时间:2014-06-28 20:27:29

标签: php

我在尝试获取数组时遇到了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;

事实上,由于显而易见的原因,它并不起作用:在两种情况下都没有初始化类。我的问题是......实现此代码运行的最佳方法是什么,而不必初始化类?

谢谢!

2 个答案:

答案 0 :(得分:1)

您正在调用非静态方法:

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

但你正在进行静态通话:

echo Core::returnAction();

当您进行静态调用时,将调用该函数(即使不是静态的)。 但由于没有对象的实例,因此没有$ this。

调用此方法的正确方法如下:

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

答案 1 :(得分:-1)

可以在不使用static keyword实例化类的情况下访问公共属性或方法。

所以你会这样做:public static $actions;

这就是说,你的类真的看起来像是被设计为实例化,因为有一个构造函数,setter,getters。

我只想改写它:

class Core{
    public static $actions;
}

享受!

@Melvin评论后更新

相关问题