pass variable by reference within class? in php
Posted
by user151841
on Stack Overflow
See other posts from Stack Overflow
or by user151841
Published on 2010-04-29T14:54:40Z
Indexed on
2010/04/29
14:57 UTC
Read the original article
Hit count: 149
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.
© Stack Overflow or respective owner