“掌握 PHP 中的干净代码:我的编码之旅的重要经验教训”重点介绍实用的实践规则和示例,以帮助 PHP 开发人员编写干净、可维护且高效的代码。在这里,我们将把这些基本规则分解为易于理解的部分,每个部分都附有一个示例。
示例:
// BAD: $x = 25; function d($a, $b) { return $a + $b; } // GOOD: $age = 25; function calculateSum($firstNumber, $secondNumber) { return $firstNumber + $secondNumber; }
描述:
示例:
// BAD: class Order { public function calculateTotal() { // logic to calculate total } public function sendInvoiceEmail() { // logic to send email } } // GOOD: class Order { public function calculateTotal() { // logic to calculate total } } class InvoiceMailer { public function sendInvoiceEmail() { // logic to send email } }
描述:
示例:
// BAD: function processOrder($order) { // Validate order if (!$this->validateOrder($order)) { return false; } // Calculate total $total = $this->calculateTotal($order); // Send invoice $this->sendInvoiceEmail($order); return true; } // GOOD: function processOrder($order) { if (!$this->isOrderValid($order)) { return false; } $this->finalizeOrder($order); return true; } private function isOrderValid($order) { return $this->validateOrder($order); } private function finalizeOrder($order) { $total = $this->calculateTotal($order); $this->sendInvoiceEmail($order); }
描述:
示例:
// BAD: if ($user->age > 18) { echo "Eligible"; } // GOOD: define('MINIMUM_AGE', 18); if ($user->age > MINIMUM_AGE) { echo "Eligible"; }
描述:
示例:
// BAD: $total = $itemPrice * $quantity; $finalPrice = $total - ($total * $discountRate); $cartTotal = $cartItemPrice * $cartQuantity; $finalCartPrice = $cartTotal - ($cartTotal * $cartDiscountRate); // GOOD: function calculateFinalPrice($price, $quantity, $discountRate) { $total = $price * $quantity; return $total - ($total * $discountRate); } $finalPrice = calculateFinalPrice($itemPrice, $quantity, $discountRate); $finalCartPrice = calculateFinalPrice($cartItemPrice, $cartQuantity, $cartDiscountRate);
描述:
示例:
// BAD: function processPayment($amount) { if ($amount > 0) { if ($this->isPaymentMethodAvailable()) { if ($this->isUserLoggedIn()) { // Process payment } } } } // GOOD: function processPayment($amount) { if ($amount <= 0) { return; } if (!$this->isPaymentMethodAvailable()) { return; } if (!$this->isUserLoggedIn()) { return; } // Process payment }
描述:
示例:
// BAD: // Increment age by 1 $age++; // GOOD: // User's birthday has passed, increase age by 1 $age++;
描述:
Example:
// Before Refactoring: function getDiscountedPrice($price, $isHoliday) { if ($isHoliday) { return $price * 0.9; } else { return $price; } } // After Refactoring: function getDiscountedPrice($price, $isHoliday) { return $isHoliday ? $price * 0.9 : $price; }
Description:
These essential rules—derived from the journey of coding cleanly in PHP—make your code more readable, maintainable, and scalable. By applying these principles consistently, you ensure that your code is easy to understand and modify over time, regardless of the complexity of your projects.
以上是掌握 PHP 中的简洁代码:我的编码之旅的主要经验教训的详细内容。更多信息请关注PHP中文网其他相关文章!