【问题标题】:Using instanceof to check and modify input使用 instanceof 检查和修改输入
【发布时间】:2017-12-29 12:02:04
【问题描述】:

我正在使用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 );
    }
  }
}

类巴兹

/**
 * 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}
                )

        )

)

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

【问题讨论】:

  • 你有什么版本的php?
  • 我正在PHP 7.1.10上尝试此代码
  • 试试instanceof Baz::class
  • @AlexanderMatrosov 给出语法错误syntax error, unexpected 'class'
  • 你绝对肯定它php7吗?

标签: php class instanceof


【解决方案1】:

你的 Foo 类应该是这样的:

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

  public function add( $bar ) {
    if (isset($this->bar[ $bar['ID'] ]) && $this->bar[ $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 );
    }
  }
}

【讨论】:

  • 从您的解决方案中的类对象中检查有效,但是我收到通知Undefined Index error 用于bar1bar2。我们能克服这个问题吗?
  • 使用array_key_exists() 而不是isset()
  • 谢谢@Alexander,它有效:) @Philipp,是的,我正在使用array_key_exists
猜你喜欢
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 2016-06-14
  • 2018-05-30
相关资源
最近更新 更多