Home  >  Article  >  Backend Development  >  PHP中字符串拼接,sprintf和直接拼接相比有什么优势/劣势吗?

PHP中字符串拼接,sprintf和直接拼接相比有什么优势/劣势吗?

WBOY
WBOYOriginal
2016-06-06 20:51:471574browse

这个问题有没有最佳实践?或者你的代码过程中是如何选择的?

个人觉得sprintf的类C printf语法更简洁

回复内容:

这个问题有没有最佳实践?或者你的代码过程中是如何选择的?

个人觉得sprintf的类C printf语法更简洁

  • 概念上不同,“.”是操作符,跟加减运算是一个级别的,“sprintf”则是函数
  • 以我做了6年的lotusphp框架为例,点操作符在150多个文件中有使用,sprintf则只在5个文件中用到了

使用场景上,sprintf是有如下优势(功能方面的):

  1. 输出特殊的格式。如无符号整数,参见案例:https://code.google.com/p/lotusphp/so...(第109行);再如,输出时字串前(或者后)补齐空格或者0,参见官方文档:http://cn2.php.net/sprintf(example 7)
  2. 多个变量合成新字串,变量在新字串中的位置是传入的参数定义的(而不是你当前正在写的代码用多个点操作符定义的)。参考案例:https://code.google.com/p/lotusphp/so...(83行)
  3. 定义好一个新字符串模板后需要多次根据这个模板合成字串。如果用点操作符就会产生冗余代码。参考案例(这个案例中有字串模板,但没有多次调用,你可以自行想象):https://code.google.com/p/lotusphp/so...

sprintf的劣势就是不如点操作符简单,例如,echo 'hello' . $_GET["username"]; include $ROOT_PATH . '/lib/db.class.php';这样的语句,我想没什么人会化简为繁用sprintf吧。

特地申请账号回答
使用点操作拼接的url无法在curl中使用,新手容易入坑!!!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn