If you want to be an excellent programmer, good coding standards are very important. So how can you write good code? In this article, we will give you some PHP coding standards and suggestions.
Coding specifications
PHP code files must start with the
<?php //开头 // 不结尾
PHP code files must be encoded in UTF-8 without BOM.
例sublime, setting增加,"show_encoding" : true
The number of characters per line should not exceed 80 characters
例,sublime "word_wrap": "true", "wrap_width": 80,
Tap key 4 spaces
例,sublime "tab_size": 4,
Only classes (traits) should be defined in PHP code /Function/Constant/Other operations that will produce side effects (such as generating file output and modifying .ini configuration files, etc.), you can only choose one.
例, a.php class A { } b.php function demo() { } c.php define('A', value); d.php ini_set('some_vars', value);
The naming of classes/trait/Interface must follow the StudlyCaps camel case naming convention starting with an uppercase letter.
class StudlyCaps { } trait StudlyCaps { } Interface StudlyCaps { }
Constants in a class must have all letters in capital letters, and words separated by underscores.
define('FOO_BAR', 'something more'); const FOO_BAR = value;
The method name (in class/trait) must conform to the camelCase-style camel case naming convention starting with lowercase.
class StudlyCaps { public function studlyCaps() { // coding... } }
Function names must conform to the snake_case-style underscore naming convention.
function snake_case() { // coding... }
Private (private) method (in class/trait) name must conform to _camelCase-style leading underscore lowercase beginning camel case Naming conventions.
class StudlyCaps { private function _studlyCaps() { // coding... } }
The first word of the method name is a verb.
class StudlyCaps { public function doSomething() { // coding... } }
Variables must conform to the camelCase-style naming convention of camel case starting with lowercase.
class StudlyCaps { public function doSomething() { $someVariable = 'demo'; // coding... } }
When a method/function has multiple parameters, there must be a space between them
class StudlyCaps { public function doSomething($variableOne, $variableTwo) { // coding... } }
- ##Operator/expression must have a space
$a = $b + $c; $a = $b . $c;
- each A blank line must be inserted after the namespace declaration block and the use declaration block.
namespace Standard; // 空一行 use Test\TestClass;//use引入类 // 空一行
- The opening curly brace "{"must be written on a line after the function declaration, and the closing curly brace"}" is also It must be written on its own line after the function body.
class StudlyCaps { }
- The opening curly brace { of the method/function must be written on its own line after the function declaration, and the closing curly brace} must also be written On a line of its own after the function body.
class StudlyCaps { public function studlyCaps() { // coding... } } function snake_case() { // coding... }
- The attributes and methods of the class must be added with access modifiers (private, protected and public), abstract and final must be declared during access before the modifier, and static must be declared after the access modifier.
abstract class StudlyCaps { abstract public function studlyCaps(); final public static function studlyCapsOne() { } }
- There must be a space after the keyword of the control structure, but there must not be when calling a method or function.
if ($valueOne === $valueTwo) { // code... } switch ($valueThree) { case 'value': // code... break; default: // code... break; } do { // code... } while ($valueFour doSomething(); do_something();
- The opening brace { of the control structure must be written on the same line as the declaration, and the closing brace } must be written after the body In a line of its own.
if ($valueOne === $valueTwo) { // code... } switch ($valueThree) { case 'value': // code... break; default: // code... break; } do { // code... } while ($valueFour <p></p>
- There must be no spaces after the opening left bracket and before the closing right bracket of the control structure.
if ($valueOne === $valueTwo) {// 控制结构(右边和)左边不加空格 // code... }Encoding suggestions
- sql is too long
// heredoc语法 $sql = <p></p>
- if and other control structure conditions are too long
if ($a > 0 && $b > 0 && $c > 0 && $d > 0 && $e > 0) { }
- Method or function parameters are greater than three Line break
public function tooLangFunction( $valueOne = '', $valueTwo = '', $valueThree = '', $valueFour = '', $valueFive = '', $valueSix = '') { //coding... }
- Chain operation exceeds two
$this->nameTest->functionOne() ->functionTwo() ->functionThree();
- After array php5.4, use []
$a = [ 'aaa' => 'aaa', 'bbb' => 'bbb' ];
- single quotes multiple quotes
- There are no variables in the string, single quotes
- There are variables in the string, double quotes
$str = 'str'; $arg = "$str";
- Declare a class or method or function, add a description & attribute description & author
/** * 类描述 * * desc */ class StandardExample { /** * 常量描述. * * @var string */ const THIS_IS_A_CONST = ''; /** * 属性描述. * * @var string */ public $nameTest = ''; /** * 构造函数. * * 构造函数描述 * @author name <email> * @param string $value 形参名称/描述 * @return 返回值类型 返回值描述 * 返回值类型:string,array,object,mixed(多种,不确定的),void(无返回值) */ public function __construct($value = '') { // coding... }</email>
- api method provides test sample example
/** * 成员方法名称. * * 成员方法描述 * * @param string $value 形参名称/描述 * * @example domain/api/controller/action?argu1=111&argu2=222 */ public function testFunction($value = '') { // code... }
- Use try...catch...
try { // coding... } catch (\Exception $e) { // coding... }
- To call multiple methods (more than 3) continuously, use foreach
// 改写doSome为doSomething class StandardExample { /** * 方法列表 * * @var array */ private $_functionList = []; public function __construct($functionList = array()) { $this->_functionList = $value; } public function doSome() { $this->functionOne(); $this->functionTwo(); $this->functionThree(); $this->functionFour(); } public function doSomething() { foreach($this->_functionList as $function) { $this->$function(); } } ... }
- Copyright statement at the top of the file
// +---------------------------------------------------------------------- // | Company Name xx服务 // +---------------------------------------------------------------------- // | Copyright (c) 2017 http://domain All rights reserved. // +---------------------------------------------------------------------- // | Author: name <email> // +----------------------------------------------------------------------</email>
以上内容就给新手程序员的一些编写代码的规范及建议,希望能帮助到大家。
相关推荐:
The above is the detailed content of PHP coding standards and suggestions for newbies. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools