php : echo"", print(), printf() [英] php : echo"", print(), printf()

查看:25
本文介绍了php : echo"", print(), printf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法用 PHP 将数据输出到 html 页面?

如果我喜欢在 php 中用 var 做一个 div,我会写类似的东西

print('

'.$var.'

');

echo "'

'.$var.'

'";

这样做的正确方法是什么?

或者更好的方法,填充一个 $tempvar 并打印一次?像这样:

$tempvar = '

'.$var.'

'打印($tempvar);

事实上,在现实生活中,var 会填满更多!

解决方案

echoprint 在 PHP 中的两个不同点:

  • print 返回一个值.它总是返回 1.

  • echo 可以采用逗号分隔的参数列表进行输出.

总是返回 1 似乎不是特别有用.并且可以使用多个调用或字符串连接来模拟逗号分隔的参数列表.所以 echoprint 之间的选择几乎归结为样式.我见过的大多数 PHP 代码都使用 echo.

printf() 是 c 的 printf() 的直接模拟.如果您熟悉 c 的习惯用法,则可以使用 printf().然而,很多年轻一代的人发现 printf() 的特殊字符语法比等效的 echo 代码可读性差.

echoprintprintf 之间的性能可能存在差异,但我不会太在意它们,因为在一个数据库驱动的 Web 应用程序(PHP 的典型域),向客户端打印字符串几乎肯定不是你的瓶颈.最重要的是,这 3 个中的任何一个都可以完成工作,并且一个并不比另一个好.这只是风格问题.

Is there a better way to output data to html page with PHP?

If I like to make a div with some var in php, I will write something like that

print ('<div>'.$var.'</div>');

or

echo "'<div>'.$var.'</div>'";

What is the proper way to do that?

Or a better way, fill a $tempvar and print it once? like that:

$tempvar = '<div>'.$var.'</div>'
print ($tempvar);

In fact, in real life, the var will be fill with much more!

解决方案

There are 2 differences between echo and print in PHP:

  • print returns a value. It always returns 1.

  • echo can take a comma delimited list of arguments to output.

Always returning 1 doesn't seem particularly useful. And a comma delimited list of arguments can be simulated with multiple calls or string concatenation. So the choice between echo and print pretty much comes down to style. Most PHP code that I've seen uses echo.

printf() is a direct analog of c's printf(). If you're comfortable in the c idiom, you might use printf(). A lot of people in the younger generation though, find printf()'s special character syntax to be less readable than the equivalent echo code.

There are probably differences in performance between echo, print and printf, but I wouldn't get too hung up on them since in a database driven web application (PHP's typical domain), printing strings to the client is almost certainly not your bottleneck. The bottom line is that any of the 3 will get the job done and one is not better than another. It's just a matter of style.

这篇关于php : echo"", print(), printf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆