Bu koşullu mantık yapısı için farklı yollar vardır ki bana oluşur. Bildiğim kadarıyla ben gördüğünüz gibi, sürece biz senaryoyu bitirmek (ya da ancak bir işlevi bir dönüş ile aynı örnekler hayal edebiliyorum) hataları set olarak, daha sonra aşağıdaki örnekler eşittir:
Example 1
if($condition1) {
trigger_error("The script is now terminated");
}
if($condition2) {
trigger_error("The script is now terminated");
}
echo "If either condition was true, we won't see this printed";
Example 2
if(!$condition1) {
if(!$condition2) {
echo "If either condition was true, we won't see this printed";
}
else {
trigger_error("The script is now terminated");
}
}
else {
trigger_error("The script is now terminated");
}
Example 3
if($condition1) {
trigger_error("The script is now terminated");
}
else {
if($condition2) {
trigger_error("The script is now terminated");
}
else {
echo "If either condition was true, we won't see this printed";
}
}
Example 4 - Fraser's Answer uyarlanmıştır
function test($condition) {
if($condition) {
trigger_error("The script is now terminated");
}
}
test($condition1);
test($condition2);
echo "If either condition was true, we won't see this printed";
Ben bu şekilde komut (veya fonksiyonu) sona koşulları kontrol ederek, açıkça koşulundan önce her şeyi, yani idam ne komut idam değil tanımlayabilirsiniz hissediyorum çünkü Şahsen, Örnek 1'deki gibi kod yazma doğru eğilmek. Bu idam ve satırdan sonra her şey değildir sahiptir. Bu benim hat 147 üzerinde bir hata olsun, ben bir hata daha hızlı bulmak için bana yardımcı oldu ne hemen biliyorum demektir. Ben aniden $ Condition1 önce $ condition2 test etmek gerekir farkındayız Ayrıca, eğer, ben basit bir kopyalama macunun bir değişiklik yapabilirsiniz.
Ben Örnek 2 de ama benim için gibi yazılmış bir sürü kod bakın, bu çok daha karmaşık hata ayıklama gibi görünüyor. Yuvalama çok büyük aldığında, bir hata altındaki bazı uzak hattında kapalı kovulacak ve iç içe kod büyük bir yığın tarafından buna neden durum ayrılamaz, çünkü bu. İlave olarak, koşullu sekansı değiştirerek çok Messier olabilir.
Bir hibrid, Örnek 3'te olduğu gibi iki tür, olabilir, ancak bu daha sonra 'başka her aslında gereksiz olduğu hususları overcomplicate gibi görünüyor.
Ben bir şey eksik? Benim koşullu kod yapısı için en iyi yolu nedir? Bu örneklerden daha iyi bir yolu var mı? Are there specific situations under which one style may be superior to another?
Edit: Örnek 4 oldukça ilginç görünüyor ve ben düşünmüştü şey değildir. Ayrıca ikinci bir parametre olarak bir hata mesajı geçebileceği.
Teşekkürler!
P.S. Böylece herhangi bir alternatif olduğunu karşılamak gerekir Ben $ Condition1 ve $ condition2 kontrol inbetween bazı keyfi adımları yapmak gerekebilir aklınızda tutun lütfen. Aksi takdirde (| | $ condition2 $ condition1) sanki trivially daha iyi alternatifler vardır.