views:

54

answers:

2

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($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 );
        }
}

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.

A: 

Just do this:

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

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.

soulmerge