有哪些有用的 PHP 习语?
我正在寻求改进我的 PHP 编码,并且想知道其他程序员使用哪些特定于 PHP 的技术来提高生产力或解决 PHP 限制。
一些示例:
处理命名空间的类命名约定:
Part1_Part2_ClassName
映射到文件Part1/Part2/ClassName.php
if ( count($arrayName) ) // 处理 $arrayName 未设置或为空
变量函数名称,例如
$func = 'foo'; $func($bar); // 调用 foo($bar);
I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.
Some examples:
Class naming convention to handle namespaces:
Part1_Part2_ClassName
maps to filePart1/Part2/ClassName.php
if ( count($arrayName) ) // handles $arrayName being unset or empty
Variable function names, e.g.
$func = 'foo'; $func($bar); // calls foo($bar);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
最终,您将首先通过学习一般良好的编程实践来充分利用 PHP,然后再关注任何特定于 PHP 的内容。 话虽如此...
为了乐趣和利润而自由地应用:
foreach 循环中的迭代器。 几乎从来没有错误的时间。
围绕类自动加载进行设计。 使用
spl_autoload_register()
,而不是__autoload()
。 为了获得奖励点,让它递归地扫描目录树,然后随意将类重新组织成更逻辑的目录结构。到处都有打字提示。 对标量使用断言。
输出 HTML 以外的内容。
学习使用异常。 编写一个将错误转换为异常的错误处理程序。
将
define()
全局常量替换为类常量。将您的 Unix 时间戳替换为正确的
Date
类。在长函数中,使用完后
unset()
变量。带着罪恶感使用:
像数组一样循环对象的数据成员。 为他们没有被宣布为私有而感到内疚。 这不是像 Python 或 Lisp 这样的异教语言。
使用输出缓冲区来组装长字符串。
除非绝对必要,否则可能不会避免,除非你真的讨厌维护程序员和你自己:
魔术方法 (
__get
,__set
,__call< /code>)
extract()
结构化数组——使用对象
Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...
Apply liberally for fun and profit:
Iterators in foreach loops. There's almost never a wrong time.
Design around class autoloading. Use
spl_autoload_register()
, not__autoload()
. For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.Typehint everywhere. Use assertions for scalars.
Output something other than HTML.
Learn to use exceptions. Write an error handler that converts errors into exceptions.
Replace your
define()
global constants with class constants.Replace your Unix timestamps with a proper
Date
class.In long functions,
unset()
variables when you're done with them.Use with guilty pleasure:
Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.
Use output buffers for assembling long strings.
Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:
Magic methods (
__get
,__set
,__call
)extract()
Structured arrays -- use an object
我的 PHP 经验教会了我一些事情。 仅举几例:
永远不要使用automagic。 像 autoLoad 这样的东西将来可能会咬你。
始终使用
require_once
请求依赖类。 这样您就可以确保直接获得依赖项。使用
if(isset($array[$key]))
而不是if($array[$key])
。 如果未定义密钥,第二个将引发警告。for
循环)给它们提供详细名称($listIndex
而不是$j
)评论,评论,评论。 如果特定的代码片段看起来不明显,请留下评论。 稍后您可能需要查看它,但可能不记得它的用途是什么。
除此之外,类、函数和变量的命名约定取决于您和您的团队。 最近我一直在使用 Zend Framework 的命名约定,因为他们对我来说是对的。
另外,在开发模式下,我设置了一个错误处理程序,它将在最轻微的错误(甚至警告)时输出错误页面,给我 完整回溯。
My experience with PHP has taught me a few things. To name a few:
Never use automagic. Stuff like autoLoad may bite you in the future.
Always require dependent classes using
require_once
. That way you can be sure you'll have your dependencies straight.Use
if(isset($array[$key]))
instead ofif($array[$key])
. The second will raise a warning if the key isn't defined.When defining variables (even with
for
cycles) give them verbose names ($listIndex
instead of$j
)Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using Zend Framework's naming conventions because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the full backtrace.
幸运的是,命名空间出现在 5.3 和 6 中。我强烈建议不要使用 Path_To_ClassName 习惯用法。 它会产生混乱的代码,并且你永远无法改变你的库结构......永远。
SPL 的自动加载功能很棒。 如果您组织得井井有条,它可以为您节省每个文件顶部典型的 20 行包含和要求块。 您还可以更改代码库中的内容,只要 PHP 可以包含这些目录中的内容,就不会出现任何问题。
充分使用
===
而不是==
。 例如:如果“needle”位于关键零处,则会给出假阴性。 相反:
将永远准确。
Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.
The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.
Make liberal use of
===
over==
. For instance:will give a false negative if 'needle' is at key zero. Instead:
will always be accurate.
请参阅此问题:PHP 的隐藏功能。 它有很多非常有用的 PHP 技巧,其中最好的已经出现在列表的顶部。
See this question: Hidden Features of PHP. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.
我在 PHP 中做的一些事情往往是 PHP 特定的。
用数组组装字符串。
在 PHP 中,许多字符串操作的成本很高,因此我倾向于编写算法来减少我进行的字符串操作的离散数量。 典型的例子是用循环构建一个字符串。 相反,从 array() 开始,并在循环中进行数组串联。 然后在最后对其进行 implode() 。 (这也巧妙地解决了尾随逗号问题。)
数组常量非常适合实现函数的命名参数。
There are a few things I do in PHP that tend to be PHP-specific.
Assemble strings with an array.
A lot of string manipulation is expensive in PHP, so I tend to write algorithms that reduce the discrete number of string manipulations I do. The classic example is building a string with a loop. Start with an array(), instead, and do array concatenation in the loop. Then implode() it at the end. (This also neatly solves the trailing-comma problem.)
Array constants are nifty for implementing named parameters to functions.
ini_set('display_errors', 1); error_reporting(E_ALL && $_STRICT);
过去 5 年我一直使用 PHP(和 MySQL)进行开发。 最近,我开始使用一个框架(Zend)和一个可靠的 javascript 库(Dojo),它永远改变了我的工作方式(我认为以一种好的方式)。
让我想到这一点的是你的第一点:Zend 框架正是这样做的,因为它是访问“控制器”和“操作”的标准方式。
在封装和抽象不同数据库的问题方面,Zend_Db 做得很好。 Dojo 在消除不同浏览器之间的 javascript 不一致方面做得非常出色。
总的来说,学习良好的 OOP 技术是值得的,并且使用(并阅读相关内容!)框架是理解 OOP 问题的一种非常实用的方法。
对于一些值得使用的独立工具,另请参阅:
Smarty(模板引擎)
ADODB(数据库访问抽象)
I've been developing with PHP (and MySQL) for the last 5 years. Most recently I started using a framework (Zend) with a solid javascript library (Dojo) and it's changed the way I work forever (in a good way, I think).
The thing that made me think of this was your first bullet: Zend framework does exactly this as it's standard way of accessing 'controllers' and 'actions'.
In terms of encapsulating and abstracting issues with different databases, Zend_Db this very well. Dojo does an excellent job of ironing out javascript inconsistencies between different browsers.
Overall, it's worth getting into good OOP techniques and using (and READING ABOUT!) frameworks has been a very hands-on way of getting to understand OOP issues.
For some standalone tools worth using, see also:
Smarty (template engine)
ADODB (database access abstraction)
在使用变量之前先声明变量!
Declare variables before using them!
了解不同的类型和
===
运算符,这对于strpos()
等某些函数至关重要,您将开始使用return false你自己。
Get to know the different types and the
===
operator, it's essential for some functions likestrpos()
and you'll start to usereturn false
yourself.