2010-04-06 12 views
6

के अंदर कॉलबैक विधियों को कैसे कार्यान्वित करें मुझे किसी अन्य विधि के अंदर किसी सरणी पर क्लास कॉलबैक विधि का उपयोग करने की आवश्यकता है (कॉलबैक फ़ंक्शन कक्षा से संबंधित है)।कक्षाओं (PHP)

class Database { 

     public function escape_string_for_db($string){ 
      return mysql_real_escape_string($string); 
     } 

     public function escape_all_array($array){ 
      return array_map($array,"$this->escape_string_for_db"); 
     } 
} 

क्या यह इस बारे में जाने का सही तरीका है? (मेरा मतलब है, array_map के लिए पारित दूसरा पैरामीटर के संदर्भ में)

उत्तर

9

मुझे नहीं लगता कि आप array_filter चाहते हैं, लेकिन array_map

return array_map(array($this, 'escape_string_for_db'), $array); 

लेकिन फिर, तुम बस के रूप में अच्छी

कर सकते हैं
return array_map('mysql_real_escape_string', $array); 
+0

धन्यवाद, मुझे दो उलझन में मिला। – Gal

0

array_filter उन तत्वों को हटा देता है जो भविष्यवाणी को पूरा नहीं करते हैं। क्या आपका मतलब array_map है?

return array_map(array($this, "escape_string_for_db"), $array); 
-1

सरल समाधान कॉलबैक के रूप में विधि पारित करने के लिए करने के लिए हो सकता है - http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback

वैकल्पिक रूप से देखते हैं, एक आवरण समारोह लिखें:

function wrap_callback($target, $use_obj=false) 
{ 
    static $obj; 
    if ($use_obj) { 
    if (method_exists($target, 'callback')) { 
     $obj=$target; 
     return true; 
    } else { 
     trigger_error("callback declared for something with no callback method"); 
     return false; 
    } 
    } 
    return $obj->callback($target); 
} 

तब:

class Database { 

    public callback($string){ 
     return mysql_real_escape_string($string); 
    } 

    public function escape_all_array($array){ 
     wrap_callback($this, true); // register callback 
     return array_filter($array,"wrap_calback"); 
    } 
} 

सी

+1

कोई अपराध नहीं, लेकिन यह अधिक जटिल है और कार्यों में स्थिर का उपयोग करना खराब शैली है – Gordon

0

यह काम करना चाहिए। आप उसी पैरामीटर में देख सकते हैं जो आपका पैरामीटर स्ट्रिंग या सरणी है।

class Database { 

    public function escape_string_for_db($data) 
    { 
    if(!is_array($data)) 
    { 
     $data =mysql_real_escape_string($data); 
    } 
    else 
    { 
     //Self call function 
     $data = array_map(array('Database ', 'escape_string_for_db'), $data); 
    } 
    return $data; 
    } 
संबंधित मुद्दे