有人能解释Php中奇怪的行为吗?

时间:2015-10-01 13:37:10

标签: php syntax

这在Python中是不可能的:

$sql = 'SELECT Linhas.NomeLinha,
               Maquinas.Nome as maquina,
               Tecnicos.Nome, 
               Avarias.DataHoraInicioAvaria,
               Avarias.DataHoraFimAvaria,
               Avarias.Descricao,
               Avarias.Solucao, 
               Avarias.TipoSolucao 
        FROM Avarias, Tecnicos, Linhas, Maquinas, avariatecnico
        WHERE Linhas.IDLinha = Avarias.IDLinha
        AND avariatecnico.IDAvaria = avarias.IDAvaria
        AND Avariatecnico.IDTecnico = Tecnicos.IDTecnico
        AND Maquinas.IDMaquina = Avarias.IDMaquina
        AND DataHoraInicioAvaria >= :datetimepicker
        AND DataHoraFimAvaria <= :datetimepicker1 ';

if ($_SESSION['IDLinha']) {
    $querydatahora = $conn->prepare($sql." AND Avarias.IDLinha = :IDLinha
                                           AND Avarias.IDMaquina = :IDMaquina
                                           ORDER BY DataHoraInicioAvaria
                                           DESC LIMIT $startrow, 9");
}else{
    $querydatahora = $conn->prepare($sql." ORDER BY DataHoraInicioAvaria
                                           DESC LIMIT $startrow, 9");
}


$params = array(':datetimepicker' => $_SESSION['datetimepicker'],
                ':datetimepicker1' => $_SESSION['datetimepicker1'],
                ':IDLinha' => $_SESSION['IDLinha'],
                ':IDMaquina' => $_SESSION['IDMaquina']
                );

$querydatahora->execute($params);

$params = array(':datetimepicker' => $_SESSION['datetimepicker'],
               ':datetimepicker1' => $_SESSION['datetimepicker1']);

if ($_SESSION['IDLinha']) {
    $querycount = $conn->prepare($sql.' AND Avarias.IDLinha = :IDLinha 
                                        AND Avarias.IDMaquina = :IDMaquina');
    $params[':IDLinha'] = $_SESSION['IDLinha'];
    $params[':IDMaquina']  $_SESSION['IDMaquina'];
}

$querycount->execute($params);

我可以用C,C ++,Java和JavaScript来测试它......

Python 2.7.3
[GCC 4.7.2] on linux2
>>> b = 15
>>> a = 15 + b = 16
  File "<stdin>", line 1
SyntaxError: can't assign to operator
>>>

但是有人可以解释一下为什么这在Php中起作用,为什么?

var b=15 ; var a = 15+ b = 15
VM155:2 Uncaught ReferenceError: Invalid left-hand side in assignment(…)

2 个答案:

答案 0 :(得分:1)

当作业发生时,PHP returns the value that was assigned

因此,如果您要echo $a = 3;,那么您将在PHP中获得3

上面链接的相同文档的另一个例子:

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

简单地说,在语言及其文档的上下文中,它是期望的行为。 Python不采用这种行为。

有趣的是,我可以使用其他功能强大的编程语言。这是Ruby:

vagrant@ubuntu-14:/vagrant$ irb
2.1.2 :001 > a = (b = 4) + 5
 => 9 
2.1.2 :002 > b
 => 4 

答案 1 :(得分:1)

您可能会说这是一个令人遗憾的功能,可能会导致您出错,但语法没有任何问题。 PHP将其评估为赋值表达式。当您说frames.name时,您正在将$a = 'some string' . $b = $c'some string'的php评估结果联系起来。