如何将全局变量转换为$ this-> php中的变量?

时间:2013-12-20 02:09:34

标签: php

我想在我的课程中将我的函数中的全局变量转换为$ 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 ."'");

    }

}

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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 ."'");

    }

}

答案 2 :(得分: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 ."'");

    }

}