Hướng dẫn dùng php codes trong PHP
Ngày đăng:
13/09/2022
Trả lời:
0
Lượt xem:
51
Hướng dẫn này kế thừa và mở rộng thêm cho Psr - 1 : Tiêu chuẩn cơ bản khi viết code. Show Tổng quan về trình bày code PHP
<?php namespace Vendor\Package; use FooInterface; use BarClass as Bar; use OtherVendor\OtherPackage\BazClass; class Foo extends Bar implements FooInterface { public function sampleFunction($a, $b = null) { if ($a === $b) { bar(); } elseif ($a > $b) { $foo->bar($arg1); } else { BazClass::bar($arg2, $arg3); } } final public static function bar() { // method body } } <?php
namespace Vendor\Package;
use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;
// ... additional PHP code ... <?php
namespace Vendor\Package;
use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;
class ClassName extends ParentClass implements
\ArrayAccess,
\Countable,
\Serializable
{
// constants, properties, methods
} Gọi phương thức và hàmKhi gọi một hàm hay phương thức của lớp, <?php bar(); $foo->bar($arg1); Foo::bar($arg2, $arg3); <?php $foo->bar( $longArgument, $longerArgument, $muchLongerArgument ); IF, ELSE, SWITCH, CASE<?php
if ($expr1) {
// if body
} elseif ($expr2) {
// elseif body
} else {
// else body;
} <?php
switch ($expr) {
case 0:
echo 'First case, with a break';
break;
case 1:
echo 'Second case, which falls through';
// no break
case 2:
case 3:
case 4:
echo 'Third case, return instead of break';
return;
default:
echo 'Default case';
break;
} WHILE <?php
while ($expr) {
// structure body
} FOR <?php for ($i = 0; $i < 10; $i++) { // for body } <?php foreach ($iterable as $key => $value) { // foreach body } TRY,CATCH <?php
try {
// try body
} catch (FirstExceptionType $e) {
// catch body
} catch (OtherExceptionType $e) {
// catch body
} Trình bày Closure<?php
$closureWithArgs = function ($arg1, $arg2) {
// body
};
$closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) {
// body
}; Lời kết cho PSR-2Có nhiều thành phần cần thực hành để trình bày code PHP như hướng dẫn, nếu ngay từ đầu học PHP bạn tuân thủ nó, nó trở thành thói quen và không còn gò bó nữa, ngược lại tạo cho bạn thói quen viết code đúng chuẩn, dễ đọc, đẹp. Vậy, ngay từ bây giờ hãy lưu tâm đến PSR-2 khi gõ các dòng code PHP nhé. |