0

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.

2
  • 1
    I just tested it out and it seems to work... I feel like a l33t h4X0r today! Commented Apr 29, 2010 at 15:17
  • you are an elite haxx0r, because i thought about this today myself! Commented Dec 19, 2014 at 20:39

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Just do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.