访问类方法内的类属性

时间:2011-04-01 16:29:27

标签: php class properties

我有一个简单的PHP类,我试图从该类的方法访问该类的属性。我已经尝试过$ this-> property_name语法,但这似乎不起作用。我做错了什么?

class NavigationBuilder {

    public $mPage;
    public $mGeoID;
    public $mContinent;
    public $mCountry;
    public $mRegion;

    private $Geograph = 'a';

    public function construct_navigation() {

    }

    public function __construct() {

        var_dump($Geograph);
    }

}

2 个答案:

答案 0 :(得分:3)

你是正确的,你需要使用$this->property。 如果您使用$this

,则示例有效
<?php

class NavigationBuilder {

    public $mPage;
    public $mGeoID;
    public $mContinent;
    public $mCountry;
    public $mRegion;

    private $Geograph = 'a';

    public function construct_navigation() {

    }

    public function __construct() {

        var_dump($this->Geograph);
    }
}

// prints string(1) "a"
$geo = new NavigationBuilder();

答案 1 :(得分:0)

试试这个:

class NavigationBuilder {

    public $mPage;
    public $mGeoID;
    public $mContinent;
    public $mCountry;
    public $mRegion;

    private $Geograph;

    public function construct_navigation() {
      $this->Geograph = 'a';
    }

    public function __construct() {

        var_dump($this->Geograph);
    }

}