2017-02-23 61 views
1

我用下面的代碼接收Warning: Illegal offset type in...警告:非法偏移類型但in_array()返回true PHP

$this->open_nodes[$new_node] 

在這種情況下是$new_node自定義對象,但我已經實現了它的__toString()方法。

現在我通常只是假設元素不是數組中,而是直接調用之前線的時候調用in_array($new_node, $this->open_nodes)被返回true。

我也有一個獨立的模塊運行具有隻到節點類的輕微差異的相同的代碼,它是運行良好。

+0

'爲值in_array'檢查,你用它作爲索引的例子。這是不一樣的。 – RST

回答

0

我想我們錯過了這裏的一些代碼,
你想用第一個$this->open_nodes[$new_node];做什麼?

的in_array會檢查是否有在你的情況的litteral陣列([a, b, n])的元素,它看起來像你想的元素添加到位置$new_node,有沒有辦法可以找到它。

你可以做什麼是數組鍵搜索,使用
in_array($new_node, array_keys($this->open_nodes))

1

PHP Array documentation

數組和對象不能用作鍵。這樣做會導致一個警告:非法偏移類型。

如果你想__toString()生效,你需要將它轉換:

$this->open_nodes[(string) $new_node]

而且in_array()正在檢查$new_nodevalues(NOT keys)的$this->open_nodes,所以必須有一些其他代碼將它放在那裏。

0

與警告

Warning: Illegal offset type in... 

你需要指定密鑰和節點分配給它。

$this->open_nodes['node_name'] = $node; 

我認爲你需要看看功能array_key_exists() 我做你的代碼,我覺得看起來像

class Example 
{ 
    protected $open_nodes = []; 

    public function __construct($open_nodes = []) 
    { 
    $this->open_nodes = $open_nodes; 
    } 

    public function check_exists($key) 
    { 
    return array_key_exists($key, $this->open_nodes); 
    } 
} 

$example = new Example([ 
    'node_one' => 'Node one test', 
    'node_two' => 'Node two test', 
]); 

if((bool)$example->check_exists('node_one')) 
{ 
    echo "Node one exists" . PHP_EOL; 
} else { 
    echo "Node one doesn't exist" . PHP_EOL; 
} 

if((bool)$example->check_exists('node_three')) 
{ 
    echo "Node three exists"; 
} else { 
    echo "Node three doesn't exist"; 
} 
相關問題