2017-12-07 8 views
0

PHP内のクラス内のすべての関数が自分の変数にアクセスできるようにします。 私は達成しようとしているImのサンプルコードを提供しています。私を助けてください。どのように私は変数をPHP内のクラス内のすべての関数にアクセスできるようにすることができます

class ClassName extends AnotherClass { 

    function __construct(argument) 
    { 

    } 

    $name = $this->getName(); 
    $city = $this->getCity(); 
    $age = 24; 


    public function getName() { 
     return 'foo'; 
    } 

    public function getCity() { 
     return 'kolkata'; 
    } 

    public function fun1() { 
     echo $name; 
     echo $city; 
     echo $age; 
    } 

    public function fun2() { 
     echo $name; 
     echo $city; 
     echo $age; 
    } 

    public function fun3() { 
     echo $name; 
     echo $city; 
     echo $age; 
    } 
} 

または最小のオーバーヘッドを持っている他の方法がある場合は、クラス属性として、あなたの変数を設定する必要が

+0

私はクラスOOPでいくつかの読書をすることをお勧めします...そしていくつかの他の人々の例....それはちょうどあなたに答えを与えるよりむしろ電球をオフに設定するかもしれません... – TimBrownlaw

+1

@AmitGuptaクラス... no globals – lagbox

+0

はい私は広範囲に検索しましたが、any.thereはコンストラクタを利用したいくつかの例を見つけられなかったので、$ this-> varを使って変数を呼び出さなければなりません。しかし、私は変数を直接$ varと呼んでいます。 @TimBrownlaw –

答えて

0

を提案しなさい:もちろん

class ClassName extends AnotherClass { 
    private $name; 
    private $city; 
    private $age; 

    //Here we do our setters and getters 
    public function setName($name) 
    {$this->name = $name;} 
    public function getName() 
    {return $this->name;} 

    // you call the setters in your construct, and you set the values there 

をあなたはプライベートとしてそれらを設定することができます、公共または保護されているかどうかは、あなたがこのクラスまたは他人からのみアクセスできるようにするかどうかによって決まります。

+2

これはまったく試しましたか?これは有効ではありませんPHP – lagbox

+1

まだ完全に無効なPHP – lagbox

+0

あなたの答えを更新してくれてありがとう:) – lagbox

2

あなたはこのようにあなたの目標をacheaveすることができます:あなたは少し軌道に乗るだろう

class ClassName extends AnotherClass { 

    private $name; 
    private $city; 
    private $age; 

    function __construct(argument) 
    { 
     $this->name = $this->getName(); 
     $this->city = $this->getCity(); 
     $this->age = 24; 
    } 

    public function getName(){ 
     return 'foo'; 
    } 
    public function getCity(){ 
     return 'kolkata'; 
    } 

    public function fun1(){ 
     echo $this->name; 
     echo $this->city; 
     echo $this->age; 
    } 
    public function fun2(){ 
     echo $this->name; 
     echo $this->city; 
     echo $this->age; 
    } 
    public function fun3(){ 
     echo $this->name; 
     echo $this->city; 
     echo $this->age; 
    } 
} 
0
class ClassName extends AnotherClass 
{ 
    protected $name; 
    protected $city; 
    protected $age = 24; 

    public function __construct() 
    { 
     $this->name = $this->getName(); 
     $this->city = $this->getCity(); 
    } 

    ... 

    public function fun1() 
    { 
     echo $this->name; 
     echo $this->city; 
     echo $this->age; 
    } 
    ... 
}