<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>
首先,让我来吐槽一下(不吐槽会死!):
$where是一个字符串,你写的$where['title']是个什么鬼?
你把一个array赋值给一个字符串中的一个字符串,这又是什么鬼?
我把你问题中的一些杂七杂八无用的代码去除后,精简一下问题:
<code>$where = '1=1'; $where['title'] = array(); var_dump($where);</code>
和上面的吐槽对应的是,我们也一步步来看:$where['title']表达的是字符串$where中下标为'title'的字符,注意下标的合法值是[0-字符串长度减1],那么php对于非法的下标,实际上是和$where[0]的作用是一致的。
这样问题进一步简化为:
立即学习“PHP免费学习笔记(深入)”;
<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"),赋值过去,这不科学把。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号