在 PHP 中,echo
和 print
是兩種常見的輸出數據到屏幕的方法
echo
:<?php
$name = "John";
echo "Hello, " . $name . "!";
?>
print
:<?php
$name = "John";
print "Hello, " . $name . "!";
?>
printf
:<?php
$name = "John";
$age = 30;
printf("Hello, %s! You are %d years old.", $name, $age);
?>
sprintf
或 vsprintf
存儲格式化字符串:<?php
$name = "John";
$age = 30;
$formatted_string = sprintf("Hello, %s! You are %d years old.", $name, $age);
echo $formatted_string;
?>
heredoc
語法:<?php
$name = "John";
$age = 30;
echo <<<EOT
Hello, $name! You are $age years old.
EOT;
?>
nowdoc
語法(PHP 5.3.0 及更高版本):<?php
$name = "John";
$age = 30;
echo <<<'EOT'
Hello, $name! You are $age years old.
EOT;
?>
這些方法都可以實現在 PHP 中高效地顯示數據。根據你的需求和代碼風格選擇合適的方法。