PHP basit artırmak / else deyimi ise

7 Cevap
<?php echo isset($areas['footer']) ? $areas['footer'] : null; ?>

Bu geliştirmek için herhangi bir şekilde?

7 Cevap

Eğer yankılanan ve yanlış durumda herhangi bir etkisi yoktur null hangi olacağını unutmayın. Yerine 'empty' veya ' ' veya 'not found' gibi diyebiliriz. Diğer alternatif dönüş değerini almak için isset:

$return = isset($areas['footer']) ? $areas['footer'] : null;

if ($return)
{
  // $return contains footer info
}
else
{
  // footer was not set :(
}

Bir değişkene atamak için temiz olabilir dan $ alanlar geliyor nereye bağlı:

$footer = isset($areas['footer']) ? $areas['footer'] : null;

Sonra herhangi bir ek isset kontrol olmadan $ altbilgi kullanabilirsiniz.

Ayrıca varsayılan ayarlayarak, başka şube yedek olabilir:

$footer = null;
if (isset($areas['footer'])) {
  $footer = $areas['footer'];
}

echo $footer;

Hayır, bu çıkış bu tür işleme en kısa yoludur.

"Ben çok sık kod bu tür kullanıyorum"

Belki bir şablon dili kullanarak, ya da bir işlevde bu davranışı kapsülleştirip tamamen sorunu önlemek gerekir?

gibi bu:

function get_area($area) {
    if... //your code
    return $area

I düşünebilirsiniz biri kısa versiyonu olacaktır:

<?php !isset($areas['footer']) or print $areas['footer']; ?>

But i'm not sure if it is faster or more elegant. What do you guys think?

echo $areas['footer'];

Basit ve orijinal çizgi tam olarak aynı etkiye sahiptir.

Edit in reply to Felix This gives a notice, but unless you're supposed to turn this in as ultra-perfect homework, it doesn't really matter. You can either fill your code with isset calls or ignore small stuff like this. I'd worry about it if I was working in say... Java, but pragmatically nobody is going to care if PHP code that works produces notices.