【问题标题】:pass variable by reference within class? in php在类中通过引用传递变量?在php中
【发布时间】:2011-02-13 20:45:11
【问题描述】:

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

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

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
    } ...
}

但我想用这种很酷的方式来做。

【问题讨论】:

  • 我刚刚测试了它,它似乎工作......我今天感觉像一个 l33t h4X0r!
  • 你是精英haxx0r,因为我今天自己也想过这个!

标签: php oop pass-by-reference


【解决方案1】:

这样做:

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

【讨论】:

    【解决方案2】:

    这是完全合法的 PHP 代码,它被称为 pass by reference 并且有多种语言版本。在 PHP 中,你甚至可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 2011-08-11
      • 2011-12-06
      • 2018-01-18
      • 1970-01-01
      • 2011-08-16
      相关资源
      最近更新 更多