使用instanceof检查和修改输入

时间:2017-12-29 12:02:04

标签: php class instanceof

我正在使用instanceof来检查类实例,并且如果类已经具有相同数据的实例,则希望修改输入数据。下面的例子详细演示了我的问题,其中我有两个独特的数组输入,第三个是第二个重复数组,其中instanceof应该工作并修改输入。

/**
 * Foo Class
 */
class Foo {
  public $bar = array();
  public function __construct() {}

  public function add( $bar ) {
    if ( $bar['ID'] instanceof Baz ) { // inctanceof not working as i am expecting. supposed to modify duplicate occurrence 

      //if bar['ID'] is already instance of Baz then we are trying to modify bar ID before pass it so Baz.
      $bar['ID'] = $bar['ID'] . rand();
      $this->bar[ $bar['ID'] ] = new Baz( $bar );
    }
    else {
      $this->bar[ $bar['ID'] ] = new Baz( $bar );
    }
  }
}

班级Baz

/**
 * Class Baz
 */
class Baz {
  public $ID;
  public function __construct( $bar ) {
    $this->ID = $bar['ID'];
  }
}

实例

$foo = new Foo();

$bar = array( 'ID'  => 'bar1' );
$foo->add( $bar );

$bar2 = array( 'ID'  => 'bar2' );
$foo->add( $bar2 );

$bar3 = array( 'ID'  => 'bar2' ); //duplicate ID
$foo->add( $bar3 );

打印

print_r( $foo );

输出

Foo Object
(
    [bar] => Array
        (
            [bar1] => Baz Object
                (
                    [ID] => bar1
                )

            [bar2] => Baz Object
                (
                    [ID] => bar2
                )

        )

)

预期产出

Foo Object
(
    [bar] => Array
        (
            [bar1] => Baz Object
                (
                    [ID] => bar1
                )

            [bar2] => Baz Object
                (
                    [ID] => bar2
                )
            [bar2{random number}] => Baz Object
                (
                    [ID] => bar2{random number}
                )

        )

)

我在这里做错了什么?请指导我,替代解决方案也适用。

1 个答案:

答案 0 :(得分:2)

你的Foo课应该是这样的:

library(EBImage)

# get image
img <- readImage("https://www.r-project.org/logo/Rlogo.png")
print(img, short = T)

# define horizontal and vertical Sobel kernel
Shoriz <- matrix(c(1, 2, 1, 0, 0, 0, -1, -2, -1), nrow = 3)
Svert <- t(Shoriz)

# get horizontal and vertical edges
imgH <- filter2(img, Shoriz)
imgV <- filter2(img, Svert)

# combine edge pixel data to get overall edge data
hdata <- imageData(imgH)
vdata <- imageData(imgV)
edata <- sqrt(hdata^2 + vdata^2)

# transform edge data to image
imgE <- Image(edata, colormode = 2)
print(display(combine(img, imgH, imgV, imgE), method = "raster", all = T))