Bir PHP fonksiyonu üzerindeki cheking ve hata

3 Cevap

Bir fonksiyon php başarısız olursa bir "IF" ile denetlemek için bir yolu var mı?

Ör.

If (getimagesize($image) returns and error)  {
echo 'Error: function dont work';
}
else
{
// do something
}

Teşekkürler!

3 Cevap

Ben özellikle herhangi bir hata kodları döndürmüyor getimagesize gibi bir işlevle, ilgilenen varsayarak ve zor bize üzerinde yapar 'm. Ama imkansız değil.

Için belgeler getimagesize şöyle:

Dosya resmine erişmek mümkün değildir, ya da geçerli bir resim değilse, getimagesize() düzeyinde bir hata üretecektir E_WARNING. Okuma hatası, getimagesize() düzeyinde bir hata üretecektir E_NOTICE.

Bu nedenle, iki şey yapmanız gerekir:

  1. Nasılsa ona hata ve hareket haberdar olsun
  2. Hatası (tüm sonra, sizin kendiniz hata işleme kodu ile herhangi bir hataları dikkat çekici olacak) görüntülenen veya aksi takdirde tüm programın yürütülmesini etkilemez değil mi

Sen set_error_handler() and restore_error_handler() . You can achieve the second with the error-control operator @ kullanarak ilk birini elde edebilir.

Yani, kod böyle bir şey gitmek gerekir:

// Set our own error handler; we will restore the default one afterwards.
// Our new error handler need only handle E_WARNING and E_NOTICE, as per
// the documentation of getimagesize().
set_error_handler("my_error_handler", E_WARNING | E_NOTICE);

// No error has occured yet; it is the responsibility of my_error_handler
// to set $error_occurred to true if an error occurs.
$error_occurred = false; 

// Call getimagesize; use operator @ to have errors not be generated
// However, your error handler WILL STILL BE CALLED, as the documentation
// for set_error_handler() states.
$size = @getimagesize(...);

// At this point, my_error_handler will have run if an error occurred, and
// $error_occurred will be true. Before doing anything with it, restore the
// previous error handler
restore_error_handler();

if($error_occurred) {
    // whatever
}
else {
    // no error; $size holds information we can use
}


function my_error_handler($errno, $errstr, $file, $line) {
    global $error_occurred;

    // If the code is written as above, then we KNOW that an error
    // here was caused by getimagesize(). We also know what error it was:
    switch($errno) {
        case E_WARNING: // Access to image impossible, or not a valid picture
        case E_NOTICE:  // Read error
    }

    // We could also check what $file is and maybe do something based on that,
    // if this error handler is used from multiple places. However, I would not
    // recommend that. If you need more functionality, just package all of this
    // into a class and use the objects of that class to store more state.

    $error_occurred = true;
    return true; // Do not let PHP's default error handler handle this after us
}

Tabii ki, bu (bir global değişken $error_occurred orada var ve bu iyi bir uygulama değil) çok sıçramalı değil. Yani çalışıyor ama aynı zamanda güzel mühendislik değil sadece bir çözüm için, bir sınıftaki tüm bu paket olacaktır. Bu sınıf tanımlamak olacaktır:

  1. (Yukarıdaki örnekte my_error_handler) hata işleyicisi uygulayan bir yöntem. Bir hata işleyicisi yerine küresel bir fonksiyonu olarak bir nesne yöntemi ayarlamak için, uygun bir ilk parametre set_error_handler çağırmanız gerekir; the documentation for callback bakın.
  2. Bayrak ve hata işleyicisi geri, sizin seçtiğiniz bazı kod yürütmesine kaydetmek, sınıf hata işleyicisi ayarlamak sağlayan bir yöntem "kodunuzu yürütülürken hata oldu". Bu yöntem, özellikle örneğin olabilir Bir callback sizin arama kodu ve parametrelerin bir dizi tarafından sağlanan almak ve arama kodu call_user_func_array to execute it. If, during execution, the error handler set from #1 above is called, mark this in a variable in your object. Your method would return the return value of call_user_func_array kullanın.
  3. Arama kodu yukarıdaki # 2 sonuçlara erişmek için kullanabileceğiniz bir yöntem ya da değişken.

O sınıf ErrorWatcher denir Yani o, sizin arama kodu gibi bir şey olurdu:

$watcher = new ErrorWatcher;
$size = $watcher->watch("getimagesize",
                        array( /* params for getimagesize here */ ));

// $size holds your result, if an error did not occur;
// check for errors and we 're done!

switch($watcher->report_last_error()) {
    // error handling logic here
}

... Güzel ve temiz ve global değişkenler ile karışıklık yok ki. Ben ErrorWatcher kendiniz sınıf yazmak için etkinleştirmek için bu yeterince iyi anlattığımı umuyorum. :-)

exceptions bir göz atın. Siz olsa işlevi onları atmak gerekecek.

İşlev bir boolean dönmek gerekiyordu değilse Edit: arada, her zaman bir şey yanlış giderse return false ve benzeri kontrol olabilir:

$result = getimagesize($image);

if ($result === false)
{
    //
}

Whatever the condition is on an "if" statement (what's inside the parenthesis) will return "true" or "false". If the condition returns "true", the first statement will be executed, otherwise the second statement will get executed.

Sen error_reporting (E_ALL), bu koyabilirsiniz; Senaryonuzun çok üstünde, sağ açılış php etiketinden sonra ne olsun hata görmek için.

Umarım yardımcı olur.

Belki böyle bir şey:

<?php
error_reporting(E_ALL);
more stuff here ...
if(your condition here){
echo "condition is true, do something";
}else{
echo "condition is not true, do something else";
}

işlev veya deyimi içinde çalıştırırsanız ya da "başka" başarısız "eğer", en azından bunu sonuç dayalı hangisi biliyor ve neden başarısız error_reporting söyleyebilir.