Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在类内通过引用传递变量?在php中_Php_Oop_Pass By Reference - Fatal编程技术网

在类内通过引用传递变量?在php中

在类内通过引用传递变量?在php中,php,oop,pass-by-reference,Php,Oop,Pass By Reference,我正在开发一个十六进制颜色类,您可以在其中更改任何十六进制代码颜色的颜色值。在我的例子中,我还没有完成十六进制数学,但它与我在这里解释的内容并不完全相关 天真地,我想开始做一些我认为做不到的事情。我想在方法调用中传递对象属性这可能吗? class rgb { private $r; private $b; private $g; public function __construct( $hexRgb ) {

我正在开发一个十六进制颜色类,您可以在其中更改任何十六进制代码颜色的颜色值。在我的例子中,我还没有完成十六进制数学,但它与我在这里解释的内容并不完全相关

天真地,我想开始做一些我认为做不到的事情。我想在方法调用中传递对象属性这可能吗?

class rgb {

        private $r;
        private $b;
        private $g;

        public function __construct( $hexRgb ) {
                $this->r = substr($hexRgb, 0, 2 );
                $this->g = substr($hexRgb, 2, 2 );
                $this->b = substr($hexRgb, 4, 2 );
        }

        private function add( & $color, $amount ) {
            $color += amount; // $color should be a class property, $this->r, etc. 
        }

        public function addRed( $amount ) {
                self::add( $this->r, $amount );
        }

        public function addGreen( $amount ) {
                self::add( $this->g, $amount );
        }

        public function addBlue( $amount ) {
                self::add( $this->b, $amount );
        }
}
如果这在PHP中是不可能的,那么它被称为什么?它可以用什么语言实现

我知道我可以做类似的事情

public function add( $var, $amount ) {
    if ( $var == "r" ) {
         $this->r += $amount
    } else if ( $var == "g" ) {
        $this->g += $amount
    } ...
}
但我想用这种很酷的方式

只要这样做:

public function add( $var, $amount ) { 
  if(property_exists(__CLASS__,$var)) $this->$var += $amount; 
}
只要这样做:

public function add( $var, $amount ) { 
  if(property_exists(__CLASS__,$var)) $this->$var += $amount; 
}

这是一个完全合法的PHP代码,它被称为,并且有多种语言可供使用。在PHP中,您甚至可以执行以下操作:

class Color {
    # other functions ...
    private function add($member, $value) {
        $this->$member += $value;
    }
    public function addGreen($amount) {
        $this->add('g', $amount);
    }
}

我将进一步使用它将构造函数中的值转换为十进制。

这是完全合法的PHP代码,它被称为,并且有多种语言可供使用。在PHP中,您甚至可以执行以下操作:

class Color {
    # other functions ...
    private function add($member, $value) {
        $this->$member += $value;
    }
    public function addGreen($amount) {
        $this->add('g', $amount);
    }
}

我将进一步使用它将构造函数中的值转换为十进制。

我刚刚测试了它,它似乎可以工作。。。我今天感觉自己像个l33t h4X0r!你是一个精英haxx0r,因为我今天也想到了这一点!我刚刚测试了一下,它似乎很有效。。。我今天感觉自己像个l33t h4X0r!你是一个精英haxx0r,因为我今天也想到了这一点!