$this面向对象PHP中的变量和变量作用域


$this variable and variable scope in Object Oriented PHP

我正在尝试编写一个类,但遇到了两个错误。

class Foo {
    protected $count;
    function __construct() {
        $this->count = sizeof($_POST['some_key']);
    }
    static function get_count() {
        echo $this->count; // Problem Line
    }
}
$bar = new Foo;
$bar->get_count(); // Problem Call

问题调用位于最后一行。在带有"//问题行"注释的行中使用$this会生成"不在对象上下文中使用$this"错误。使用"self::count"代替"this->count"会生成"未定义的类常量错误"。我可能做错了什么?

>get_count是静态的。静态方法属于类,而不是实例。因此,在静态方法调用中,没有this。同样,不能从静态方法中引用具体成员变量(如 count)。

在您的示例中,我真的不明白为什么使用 static 关键字(因为您所做的只是回显成员变量)。删除它。

我建议您执行以下操作:

class Foo {
    protected $count;
    function __construct($some_post) {
        $this->count = sizeof($some_post);
    }
    function get_count() {
        echo $this->count;
    }
}
$some_post = $_POST['some_key'];
$bar = new Foo;
$bar->get_count($some_post);

或:

class Foo {
    protected $count;
    function __construct() {
        global $_POST;
        $this->count = sizeof($_POST['some_key']);
    }
    function get_count() {
        echo $this->count;
    }
}
$bar = new Foo;
$bar->get_count();