闹鬼!php字符串数组交叉

WBOY
Libérer: 2016-08-04 09:20:08
original
1011 Les gens l'ont consulté

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

var_dump($where);

竟然打印出来:A=1

到底是怎么样的转换流程?</code>
Copier après la connexion
Copier après la connexion

回复内容:

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

var_dump($where);

竟然打印出来:A=1

到底是怎么样的转换流程?</code>
Copier après la connexion
Copier après la connexion

首先,让我来吐槽一下(不吐槽会死!):

  1. $where是一个字符串,你写的$where['title']是个什么鬼?

  2. 你把一个array赋值给一个字符串中的一个字符串,这又是什么鬼?

我把你问题中的一些杂七杂八无用的代码去除后,精简一下问题:

<code>$where = '1=1';
$where['title'] = array();
var_dump($where);</code>
Copier après la connexion

和上面的吐槽对应的是,我们也一步步来看:
$where['title']表达的是字符串$where中下标为'title'的字符,注意下标的合法值是[0-字符串长度减1],那么php对于非法的下标,实际上是和$where[0]的作用是一致的。
这样问题进一步简化为:

<code>$where = '1=1';
$where[0] = array();
var_dump($where);</code>
Copier après la connexion

了解了$where[0]实际上指的是$where字符串的第一个字符,那么下面就是要吐槽的“你把一个array赋值给一个字符串中的一个字符串,这又是什么鬼?
我们下面做一个测试:

<code>var_dump( (string)array() );</code>
Copier après la connexion

你猜会输出什么?

<code>PHP Notice:  Array to string conversion in /home/nfer/temp.php on line 8
string(5) "Array"</code>
Copier après la connexion

那么这里就很好理解了,$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>
Copier après la connexion

你觉得结果会输出什么呢?

1.$where = 1,这个没错把,首先这个是字符串。
2.然后你又把$where当数组,并把$where['title'] = array('like',"xxx"),赋值过去,这不科学把。

Étiquettes associées:
php
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!