【发布时间】: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