开发者

pass variable by reference within class? in php

I'm working on a hex color class where you can change the color values of any hex code color. In my example, I haven't finished the hex math, but it's not completely relevant to what I'm explaining here.

Naively, I wanted to start to do something that I don't think can be done. I wanted to pass object properties in a method call. Is this possible?

class rgb {

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

        public function __construct( $hexRgb ) {
                $this->r = substr($hexRgb, 0, 2 );
                $this->g = substr($he开发者_StackOverflow社区xRgb, 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 );
        }
}

If this is not possible in PHP, what is this called and in what languages is it possible?

I know I could do something like

public function add( $var, $amount ) {
    if ( $var == "r" ) {
         $this->r += $amount
    } else if ( $var == "g" ) {
        $this->g += $amount
    } ...
}

But I want to do it this cool way.


This is perfectly legal PHP code, it is called pass by reference and is available in many languages. In PHP, you can even do something like this:

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

I would further use hexdec() to convert the values in your constructor to decimal.


Just do this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜