简体   繁体   中英

Are there helpful PHP naming conventions?

I come from Java / Objective-C to PHP and find it horrible . I mean, PHP is nice, really. But when you look at a bunch of variables, you don't know: Is that an number? Is that an string? Or ist that even a fancy object that can perform actions when calling methods on it?

So I wonder if there are helpful re-usable naming conventions for variables to help figure out if something is an object, or if something is just a boring variable. I'd say if something is an object, ie an instance of a class, the first character must be BIG. But it's just a guess. Hope to read some tips from PHP pros :-)

As in other languages, there is no single coding standard in PHP. You can, among others (see the comments), check out the Zend coding standards , they are quite highly regarded as they are very close to (and partly identical with) the PHP core development team.

What's to prevent you from using the conventions you're already familiar with? It's likely that there is nothing unique to PHP that you've not already witnessed before.

I usually stick to this simple rule

Meaningfull Camel Case Variable names (with type prefix before) ex : intNbDaysLeft would be good for an integer

I use Zend Eclipse, so I describe my variables like this, to make sure they're intellisensed. Then, I worry less about, "what is this?"

/**
 * @var Zend_Form_Element
 */
protected $_member;

or

/**
 * @param Zend_Form_Element $input
 */
function do_it( $input )

or

$my_var = some_function(); /* @var $my_var Zend_Form_Element */

You should quickly discover that there is little type hinting in PHP, and the reason for that is clear, in this dynamic language type can change, so name is not very important.

Using PHPDoc with Eclipse or NetBeans helps, but you cant rely on that, if you want to be sure that Your variable is of specific type, you have to check it (is_array(), instanceof, ect.).

Also, PHP does a lot for you, it will convert betwen types on Your behalf, it will act differently depending on the type.

PHP mostly works with strings, so most variables are of that type. Applications can have lots of types, but a single method shouldn't use too many. If you find yourself using so many objects that you cant easily keep track of their instance names, then it's some design problem, not naming convention issue.

If you want to be sure you have not used some variable wrongly, be sure to unit test. The standard in PHP is phpunit

我最喜欢的PHP命名约定是“PHP”总是被称为“巨大的cr-我们不会用bargepole接触”的约定。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM