2013-02-09 113 views
0

我是OOP的新手,需要對一些概念進行一些說明。我有一個帶有私有變量和兩個簡單​​函數的簡單類。函數將私有變量的值設置爲40.現在如何訪問函數2中的變量值,使變量值爲40?如何在類中的另一個函數中訪問函數的變量?

class MyClass { 

    //declaring private variable: 
    private $var = ''; 

    function MyfuncOne(){ 
     $this->var = "40"; 
    } 

    function MyfuncTwo(){ 
    } 
} 

我如何獲得的$this->var這是40在MyfuncOne聲明()的值?

回答

2

在兩個作用,你可以訪問它想:

function MyFuncTwo() { 
    print $this -> var; // Just access it, its a member variable of the same class 
} 

變量是私有的,從這個類(無法訪問)繼承其他類,但與其他成員函數完全訪問。在默認構造函數

編輯 如果你想將值設置爲40,而不首先調用該函數,你可能需要一個默認的構造函數。

參見:http://php.net/manual/en/language.oop5.decon.php

簡單:

class MyClass {  
    //declaring private variable: 
    private $var = ''; 

    // This is the default constructor, it gets called when you create the object 
    function __construct() { 
     $this -> var = "40"; 
    } 

    function MyfuncOne(){ 
     $this->var = "40"; 
    } 

    function MyfuncTwo(){ 
    } 

    function get_var() { 
     return $this -> var; 
    } 
} 

然後,當你讓你的對象時,它會被設置爲 「40」:

$obj = new MyClass(); 
print "The object's var is " . $obj -> get_var(); // Notice we didn't have to call MyFuncOne(), it's just set. 
+0

三江源但如果我只是被訪問$ this-> var在函數2中,我不會得到$ this-> var = 40 – Mark 2013-02-09 19:49:55

+0

如果你先調用函數1,你會的。您可能正在尋找一個默認構造函數(http://php.net/manual/en/language.oop5.decon.php),它可以設置首次創建對象時的值。 – Julio 2013-02-09 19:50:45

+0

謝謝你的幫助,但是有沒有一種方法可以將$ this-> var的值設置爲40而不必先調用函數呢? – Mark 2013-02-09 19:54:04

相關問題