การปรับปรุงการดำเนินการซ้ำใน PHP
บ่อยครั้งที่โปรแกรมเมอร์มือใหม่เรียกใช้ฟังก์ชันเดียวกันซ้ำๆ โดยไม่คิด ทำให้สิ้นเปลืองทรัพยากร
ลองดูตัวอย่าง พิจารณารหัสต่อไปนี้:
<?php
$arr = [1, 2, 3, 4, 5];
if (count($arr) >= 1 and count($arr) <= 3) {
}
?>
มีปัญหาอะไรในรหัสนี้? ปัญหาคือเรา
ทำสิ่งเดียวกันสองครั้ง - นับความยาว
ของอาร์เรย์ด้วย count($arr) การ
ดำเนินการนี้ใช้เวลาและควรทำ
เพียงครั้งเดียว เก็บผลลัพธ์ไว้ในตัวแปร
จากนั้นใช้ตัวแปรนี้ใน
ตำแหน่งที่ต้องการ ดังนี้:
<?php
$arr = [1, 2, 3, 4, 5];
$len = count($arr);
if ($len >= 1 and $len <= 3) {
}
?>
ปรับปรุงรหัสด้านล่าง:
<?php
if (date('Y') >= 2018 and date('Y') <= 2020) {
echo 'year ' . date('Y') . ' is suitable';
} else {
echo 'year ' . date('Y') . ' is not suitable';
}
?>
ปรับปรุงรหัสด้านล่าง:
<?php
$password = 'abcde';
if (strlen($password) >= 2 and strlen($password) <= 10) {
echo 'password length is acceptable';
} else {
echo 'invalid password length';
}
?>