2010-11-05 92 views
2

我想創建一個類來存儲許多地方使用的多語言詞彙的小列表,我想要替換程序中當前使用的大量'include'語句。這是我在想什麼(它不是全功能的)。你能幫助我做出工作並使用適當的面向對象構造。設置詞彙列表的PHP OO類

class VocabClass{ 

    public $term = array();  

    public function __construct(){ 
    // my vocabulary... 
    $this->term['hello']['E'] = 'hello'; 
    $this->term['hello']['F'] = 'bonjour'; 
    $this->term['goodbye']['E'] = 'goodbye'; 
    $this->term['goodbye']['F'] = 'aurevoir';  
    } 
} 

class Program{ 

public $vocab; 
function __construct(){ 
    $vocab = new VocabClass();  
    // this works 
    echo $vocab->term['hello']['F']; 
} 

function Main() { 

    // this doesn't work 
    echo $vocab->term['hello']['E']; 
    echo $this->term['hello']['E']; 


} 
} 


$myProgram = new Program(); 
$myProgram->Main(); 

?> 

回答

1

$這是在參考了當前對象(從對象之內)。既然你在對象中有$ vocab屬性,你可以說$ this-> vocab來訪問這個屬性。您也可以在沒有$ this的情況下執行此操作,但$ this(恕我直言)讓您更清楚地瞭解您在開始繼承對象時所引用的對象。

另外,如果這些是硬編碼值而不是從數據庫中提取,爲什麼不使用其中定義的語言文件?如:

語言/ english.php

define('LANG_YES', 'Yes'); 
define('LANG_NO', 'No'); 
define('LANG_CANCEL', 'Cancel'); 
define('LANG_WELCOME', 'Welcome!'); 

語言/ french.php

define('LANG_YES', 'Oui'); 
define('LANG_NO', 'N'); 
define('LANG_CANCEL', 'Annuler'); 
define('LANG_WELCOME', 'Bienvenue'); 

然後包括正確的文件在你的 「的common.php」 或 「includes.php」 文件。從那裏你可以在整個頁面中使用常量。你甚至可以通過使擴展它(如果是這種情況)的英文文件的默認並執行

if (!defined('LANG_YES')) define('LANG_YES','Yes'); 

然後你就可以加載其他語言的第一,然後在上面english.php(所以你可以確保你有至少一個默認值應在不真正轉化)

2
在主功能

,試試這個...

function Main(){ 
    echo $this->vocab->term['hello']['E']; 
} 
2

試試這個:你需要始終引用值和方法,一類中使用$這個 - >

class VocabClass{ 

    public $term = array(); 

    public function __construct(){ 
    // my vocabulary... 
    $this->term['hello']['E'] = 'hello'; 
    $this->term['hello']['F'] = 'bonjour'; 
    $this->term['goodbye']['E'] = 'goodbye'; 
    $this->term['goodbye']['F'] = 'aurevoir'; 
    } 
} 

class Program{ 

public $vocab; 
function __construct(){ 
    $this->vocab = new VocabClass(); 
} 

function Main() { 

    // this doesn't work 
    echo $this->vocab->term['hello']['E']; 
} 
} 

但進一步得到了,爲什麼不把它更少排列 - ish:

$p = new Program(); 
$p->Main(); 

class VocabClass { 
    const ENGLISH = 1; 
    const FRENCH = 2; 

    public $hello; 
    public $goodbye; 

    public function __construct($language) { 
     switch ($language) { 
      case self::ENGLISH: 
       $this->hello = 'hello'; 
       $this->goodbye = 'goodbye'; 
       break; 
      case self::FRENCH: 
       $this->hello = 'bonjour'; 
       $this->goodbye = 'aurevoir'; 
     } 
    } 
} 

class Program { 
    public $vocab; 

    function __construct() { 
     $this->vocab = new VocabClass(VocabClass::ENGLISH); 
    } 

    function Main() { 
     echo $this->vocab->hello; 
    } 
}