【问题标题】:Using a php class object in for each loop在每个循环中使用 php 类对象
【发布时间】:2014-01-05 23:45:15
【问题描述】:

我有一个类(颜色),其中包含一堆用于颜色处理的函数。我有一个单独的函数来返回图像颜色数组。

调色板功能已成功运行 - 将数组输出到 $pallette。

没有循环,我可以手动将 $palletteColor var 设置为十六进制,getClosestMatch 函数返回我的参考数组中最接近的颜色。一切都好。

当我把它放到一个循环中时,我没有得到正确的结果——似乎每个循环的返回都是相同的,所以我从 getClosestMatch 中得到了 10 个相同的值。 $palette 来自类外部的函数,因此仍按应有的方式运行。 - 编辑:澄清 - $pallette 数组值不一样 - 请参阅下面的 var_dump。

我想我可能误解了创建新类对象的工作原理或应该影响返回的变量。谁能解释一下这个过程应该如何运作?

编辑! 基于以下...当我使用硬编码的单个值进行测试时,它是一个整数(0x003cfe)。在循环中我添加('0x'.$palleteColor)。这是否使它成为一个字符串?我怎样才能将它构造为一个 int 来测试?

foreach($palette as $palleteColor) 
 { 

  $color1 = new Color('0x'.$palleteColor);
  $closestmatch = $color1->getClosestMatch($colors);
  echo "<tr><td style='background-color:#$palleteColor;width:2em;'>&nbsp;        
  </td><td>#$palleteColor $closestmatch</td></tr>\n"; 
 } 

类构造函数:

public function __construct($intColor = null)
    {
        if ($intColor) {
            $this->fromInt($intColor);
        }
    }

fromINT 函数:

public function fromInt($intValue)
{
    $this->color = $intValue;

    return $this;
}

getClosestMatch 函数:

public function getClosestMatch(array $colors)
{
    $matchDist = 15;
    $matchKey = null;
    foreach($colors as $key => $color) {
        if (false === ($color instanceof Color)) {
            $c = new Color($color);
        }
        $dist = $this->getDistanceLabFrom($c);
        if ($dist < $matchDist) {
            $matchDist = $dist;
            $matchKey = $key;
        }
    }
    echo $dist;
    return $matchKey;
}

$pallette 的 var_dump:

array(10) { [0]=> string(6) "ffffff" [1]=> string(6) "ff3333" 
[2]=> string(6) "cc3333" [3]=> string(6) "ff6666" [4]=> string(6) "cc6666" 
[5]=> string(6) "ffcccc" [6]=> string(6) "ffffcc" [7]=> string(6) "ff9999" 
[8]=> string(6) "ff6633" [9]=> int(993333) }

【问题讨论】:

标签: php arrays function class


【解决方案1】:

问题解决了:

最初使用硬编码值测试 -

$color1 = new Color(0x003cfe)

使用的循环版本:

$color1 = new Color('0x'$palleteColor);

这使它成为字符串而不是整数 修正:

$color1 = new Color(hexdec($palleteColor));

谢谢大家。

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2017-12-16
    • 2016-01-10
    • 1970-01-01
    • 2021-10-06
    • 2017-09-04
    • 2021-07-11
    • 2012-01-14
    • 2012-03-30
    相关资源
    最近更新 更多