development

참조 : PHP의 인쇄 및 에코 비교

big-blog 2020. 5. 20. 08:17
반응형

참조 : PHP의 인쇄 및 에코 비교


PHP printecho? 의 차이점은 무엇입니까 ?

스택 오버플로에는 PHP printecho키워드 사용법 에 대한 많은 질문이 있습니다.

이 게시물의 목적은 PHP 키워드 에 대한 표준 참조 질문과 답변 을 제공 하고 차이점과 사용 사례를 비교하는 것입니다.printecho


왜 두 가지 구조입니까?

인쇄반향 에 대한 진실은 사용자에게 두 개의 서로 다른 구성으로 보이지만 기본에 도달하면 내부 반향 코드를 보면 반향의 음영입니다. 이 소스 코드에는 파서 및 opcode 처리기가 포함됩니다. 숫자 0을 표시하는 것과 같은 간단한 조치를 고려하십시오. echo 또는 print를 사용하든 동일한 핸들러 "ZEND_ECHO_SPEC_CONST_HANDLER"가 호출됩니다. print 처리기는 echo 처리기를 호출하기 전에 한 가지 작업을 수행하며 다음과 같이 print의 반환 값이 1인지 확인합니다.

ZVAL_LONG(&EX_T(opline->result.var).tmp_var, 1);

(참고 를 위해 여기를 보십시오 )

리턴 값은 조건식에서 print를 사용하려는 경우 편리합니다. 왜 100이 아닌 1입니까? PHP에서 1 또는 100의 진실성은 동일합니다. 즉, 부울 컨텍스트의 0은 거짓 값과 같습니다. PHP에서 0이 아닌 모든 값 (양수와 음수)은 진실한 값이며 이는 PHP의 Perl 레거시에서 파생됩니다.

그러나 이것이 사실이라면, 왜 echo가 여러 인수를 취하는 지 궁금해 할 수 있지만 print는 하나만 처리 할 수 ​​있습니다. 이 답변을 위해 파서, 특히 파일 zend_language_parser.y로 설정해야 합니다. echo에는 유연성이 내장되어있어 하나 또는 여러 개의 표현식을 인쇄 할 수 있습니다 ( 여기 참조 ). 인쇄는 하나의 인쇄 식으로 제한되는 반면 (참조 : ).

통사론

C 프로그래밍 언어와 PHP와 같은 영향을받는 언어에는 문장과 표현이 구분됩니다. 구문 적으로 echo expr, expr, ... expr는 명령문이지만 print expr값으로 평가되므로 표현식입니다. 따라서 다른 진술과 마찬가지로 echo expr자체적으로 표현에 표현할 수 없습니다.

5 + echo 6;   // syntax error

반대로, print expr혼자서도 성명서를 작성할 수 있습니다.

print 5; // valid

또는 표현식의 일부가 되십시오.

   $x = (5 + print 5); // 5 
   var_dump( $x );     // 6 

하나의 생각을 유혹 할 수있는 print것처럼, 단항 연산자 인 것처럼 !또는 ~이 연산자 아닙니다 그러나. 어떤 !, ~ and print공통점이 모든 PHP에 내장되어 각 단 하나의 인수를 취하는 것입니다. print다음과 같이 이상하지만 유효한 코드를 만드는 데 사용할 수 있습니다 .

    <?php 
    print print print print 7; // 7111

언뜻보기에는 마지막 print 문이 피연산자 '7'을 먼저 인쇄하는 것이 이상하게 보일 수 있습니다 . 그러나 더 깊이 파고 실제 opcode를 보면 의미가 있습니다.

line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   3     0  >   PRINT                                            ~0      7
         1      PRINT                                            ~1      ~0
         2      PRINT                                            ~2      ~1
         3      PRINT                                            ~3      ~2
         4      FREE                                                     ~3
         5    > RETURN                                                   1

생성되는 첫 번째 opcode는 'print 7'에 해당합니다. '~ 0'은 값이 1 인 임시 변수입니다. 해당 변수는 다음 인쇄 opcode에 대해 피연산자가되어 임시 변수를 반환하고 프로세스가 반복됩니다. 마지막 임시 변수는 전혀 사용되지 않으므로 해제됩니다.

print값을 반환 echo합니까?

표현식은 값으로 평가됩니다. 예를 들어로 2 + 3평가 5하고로 abs(-10)평가합니다 10. print expr자체가 표현식 이므로 값을 보유해야합니다. 일관된 값은 1진실한 결과 나타내며 0이 아닌 값을 반환하면 다른 표현식에 포함하는 데 유용합니다. 예를 들어이 코드 조각에서 print의 반환 값은 함수 순서를 결정하는 데 유용합니다.

<?php

function bar( $baz ) { 
   // other code   
}
function foo() {
  return print("In and out ...\n");
}

if ( foo() ) {

     bar();
}

다음 예제와 같이 즉시 디버깅 할 때 특정 값의 인쇄를 찾을 수 있습니다.

<?php
$haystack = 'abcde';
$needle = 'f';
strpos($haystack,$needle) !== FALSE OR print "$needle not in $haystack"; 

// output: f not in abcde

As a side-note, generally, statements are not expressions; they don't return a value. The exception, of course are expression statements which use print and even simple expressions used as a statement, such as1;, a syntax which PHP inherits from C. The expression statement may look odd but it is very helpful, making it possible to pass arguments to functions.

Is print a function?

No, it is a language construct. While all function calls are expressions, print (expr) is an expression, despite the visual which appears as if it were using function call syntax. In truth these parentheses are parentheses-expr syntax, useful for expression evaluation. That accounts for the fact that at times they are optional if the expression is a simple one, such as print "Hello, world!". With a more complex expression such as print (5 ** 2 + 6/2); // 28 the parentheses aid the evaluation of the expression. Unlike function names, print is syntactically a keyword, and semantically a "language construct".

The term "language construct" in PHP usually refers to "pseudo" functions like isset or empty. Although these "constructs" look exactly like functions, they are actually fexprs, that is, the arguments are passed to them without being evaluated, which requires special treatment from the compiler. print happens to be an fexpr that chooses to evaluate its argument in the same way as a function.

The difference can be seen by printing get_defined_functions(): there is no print function listed. (Though printf and friends are: unlike print, they are true functions.)

Why does print(foo) work then?

For the same reason thatecho(foo) works. These parentheses are quite different from function call parentheses because they pertain to expressions instead. That is why one may code echo ( 5 + 8 ) and can expect a result of 13 to display (see reference). These parenthesis are involved in evaluating an expression rather than invoking a function. Note: there are other uses for parentheses in PHP, such as if if-conditional expressions, assignment lists, function declarations, etc.

Why do print(1,2,3) and echo(1,2,3) result in syntax errors?

The syntax is print expr, echo expr or echo expr, expr, ..., expr. When PHP encounters (1,2,3), it tries to parse it as a single expression and fails, because unlike C, PHP does not really have a binary comma operator; the comma serves more as a separator. ( You may find a binary comma nonetheless in PHP's for-loops, syntax it inherited from C.)

Semantics

The statement echo e1, e2, ..., eN; can be understood as syntactic sugar for echo e1; echo e2; ...; echo eN;.

Since all expressions are statements, and echo e always has the same side-effects as print e, and the return value of print e is ignored when used as a statement, we can understand echo e as syntactic sugar for print e.

These two observations mean that echo e1, e2, ..., eN; can be seen as syntactic sugar for print e1; print e2; ... print eN;. (However, note the non-semantic runtime differences below.)

We therefore only have to define the semantics for print. print e, when evaluated:

  1. evaluates its single argument e and type-casts the resulting value to a string s. (Thus, print e is equivalent to print (string) e.)
  2. Streams the string s to the output buffer (which eventually will be streamed to the standard output).
  3. Evaluates to the integer 1.

Differences at the bytecode level

print involves a small overhead of populating the return variable (pseudocode)

print 125;

PRINT  125,$temp     ; print 125 and place 1 in $temp 
UNSET  $temp         ; remove $temp

single echo compiles to one opcode:

echo 125;

ECHO 125

multi-value echo compiles to multiple opcodes

echo 123, 456;

ECHO 123
ECHO 456

Note that multi-value echo doesn't concatenate its arguments, but outputs them one-by-one.

Reference: zend_do_print, zend_do_echo.

Runtime differences

ZEND_PRINT is implemented as follows (pseudocode)

PRINT  var, result:

    result = 1
    ECHO var

So it basically puts 1 in the result variable and delegates the real job to the ZEND_ECHO handler. ZEND_ECHO does the following

ECHO var:

    if var is object
        temp = var->toString()
        zend_print_variable(temp)
    else
        zend_print_variable(var)

where zend_print_variable() performs the actual "printing" (in fact, it merely redirects to a dedicated SAPI function).

Speed: echo x vs print x

Unlike echo, print allocates a temporary variable. However, the amount of time spent on this activity is minuscule, so the difference between these two language constructs is negligible.

Speed: echo a,b,c vs echo a.b.c

The first one compiles down to three separate statements. The second evaluates the entire expression a.b.c., prints the result and disposes it immediately. Since concatenation involves memory allocations and copying, the first option will be more efficient.

So which one to use?

In web applications, output is mostly concentrated in templates. Since templates use <?=, which is the alias of echo, it seems logical to stick to echo in other parts of code as well. echo has an additional advantage of being able to print multiple expression without concatenating them and doesn't involve an overhead of populating a temporary return variable. So, use echo.


I know I am late but one thing I would like to add is that in my code

 $stmt = mysqli_stmt_init($connection) or echo "error at init"; 

gives an error "syntax error, unexpected 'echo' (T_ECHO)"

while

 $stmt = mysqli_stmt_init($connection) or print "error at init";

works fine.

Docs about echo says "echo (unlike some other language constructs) does not behave like a function" here but about print docs also says "print is not actually a real function (it is a language construct)" here. So I am not sure why. And also about echo and print docs says "The major differences to echo are that print only accepts a single argument and always returns 1." here

I would be happy if anyone can shed some light about this behavior.

참고URL : https://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo

반응형