首頁  >  文章  >  後端開發  >  鬧鬼! php字串陣列交叉

鬧鬼! php字串陣列交叉

WBOY
WBOY原創
2016-08-04 09:20:081011瀏覽

<code>$where = '1=1';
$keyword = $_GET['keyword'];
        
if($keyword) {
    $where['title'] = array('like', "%$keyword%");
}

var_dump($where);

竟然打印出来:A=1

到底是怎么样的转换流程?</code>

回覆內容:

<code>$where = '1=1';
$keyword = $_GET['keyword'];
        
if($keyword) {
    $where['title'] = array('like', "%$keyword%");
}

var_dump($where);

竟然打印出来:A=1

到底是怎么样的转换流程?</code>

首先,讓我來吐槽一下(不吐槽會死!):

  1. $where是一個字串,你寫的$where['title']是個什麼鬼?

  2. 你把一個array賦值給一個字串中的一個字串,這又是什麼鬼?

我把你問題中的一些雜七雜八無用的程式碼去除後,精簡一下問題:

<code>$where = '1=1';
$where['title'] = array();
var_dump($where);</code>

和上面的吐槽對應的是,我們也一步步來看:
$where['title']表達的是字符串$where中下標為'title'的字符,注意下標的合法值是[0-字串長度減1],那麼php對於非法的下標,實際上是和$where[0]的作用是一致的。
這樣問題進一步簡化為:

<code>$where = '1=1';
$where[0] = array();
var_dump($where);</code>

了解了$where[0]實際上指的是$where字符串的第一個字符,那麼下面就是要吐槽的“你把一個array賦值給一個字符串中的一個字符串,這又是什麼鬼?

<code>var_dump( (string)array() );</code>
你猜會輸出什麼?

<code>PHP Notice:  Array to string conversion in /home/nfer/temp.php on line 8
string(5) "Array"</code>
那麼這裡就很好理解了,

$where[0] = array();

就是把字串

Array賦值給$where字串的第一個字元。 bingo, the output is string(3) "A=1"
最後,請我也寫一個鬧鬼

的程式碼:

<code>$where = 'A=1';
$keyword = $_GET['keyword'];
        
if($keyword) {
    $where['title'] = $keyword == 123;
}

var_dump($where);</code>
你覺得結果會輸出什麼呢?

1.$where = 1,這個沒錯把,首先這個是字串。

2.然後你又把$where當數組,並把$where['title'] = array('like',"xxx"),賦值過去,這不科學把。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn