2013-12-20 35 views
1

我想在我的類中的函數中將全局變量轉換爲$ this->變量。這可能嗎?這是我爲班上的代碼。

class tool 
{ 

//If this is used remember to replace Void with $target 

    public function mute() 
    { 

     global $target; 
     mysql_query("UPDATE users SET mute='1' WHERE name='". $target ."'"); 

    } 

} 
+0

看到看代碼示例:http://3v4l.org/p7oH4 – floww

回答

6

做的最好的辦法是將它作爲參數傳遞給你的構造函數,並將其分配給一個成員變量:

class Tool 
{ 
    protected $target; 

    public function __construct($target) 
    { 
     $this->target = $target; 
    } 

    public function mute() 
    { 
     // Do stuff. I recommend not using mysql_*. Look into mysqli_* or PDO 
     mysql_query("UPDATE users SET mute='1' WHERE name='". $this->target ."'"); 
    } 
} 

$tool = new Tool($target); 
+0

哇,我寫了與你完全相同的代碼......這很有趣!我刪除了我的答案,贊成你的,因爲你先發布。 – mc10

+0

@ mc10我想這意味着我們可能會做些什麼! ;) –

+0

由於某種原因,它沒有更新數據庫中的信息:l有什麼建議嗎? – M4TRIX

2
<?php 
/** 
* Please, read this too : http://git.php.net/?p=php-src.git;a=blob_plain;f=CODING_STANDARDS;hb=HEAD 
* 
* Classes should be given descriptive names. Avoid using abbreviations where 
* possible. Each word in the class name should start with a capital letter, 
* without underscore delimiters (CamelCaps starting with a capital letter). 
* The class name should be prefixed with the name of the 'parent set' (e.g. 
* the name of the extension):: 
*/ 
class Tool{ 

    private $target; 

    public function __construct($target){ 
     $this->target = $target; 
    } 

    public function mute(){ 
     mysql_query("UPDATE users SET mute='1' WHERE name='". $this->target ."'"); 

    } 

} 
0

我做你想要的假設$this->target的值始終與global $target匹配,即使稍後更改了全局。初始化類時,設置對全局$ target的引用。

class tool 
{ 

    protected $target;   

    public function __construct() 
    { 
     $this->target = &$GLOBALS['target']; 
    } 

    public function mute() 
    { 

     mysql_query("UPDATE users SET mute='1' WHERE name='". $this->target ."'"); 

    } 

}