Override PHP Function


Hits: 3343  

PHP have PECL (PHP Extension & Community Library) function to override built-in functions by replacing them in the symbol table.

bool override_function ( string $function_name , string $function_args , string $function_code )

 

  1. <?php
  2. override_function(‘strlen’, ‘$string’, ‘return override_strlen($string);’);
  3. function override_strlen($string){
  4. return strlen($string);
  5. }
  6. ?>

The above function “override_function()” require APD i.e. Advanced PHP Debugger.

We can find more about APD here…
http://pecl.php.net/package/apd

Linux users can install apd using below command

# pecl install apd

There is an alternate way to override PHP functions, we can use below class “override” to override any built-in PHP function if PECL is not installed on server 😉

 

  1. <?php
  2. $or = new override ();
  3. $or->override_function(‘strlen’, ‘override_strlen‘, ‘return override_strlen($string);’);
  4. function override_strlen($string){
  5. return strlen($string);
  6. }
  7. ?>

 

 

<?php

$url = 'http://www.svnlabs.com';
$override = new override();

 

$override->override_function('file_get_contents','fileGetContents',$url);

if ($over_func_name = $override->override_check('file_get_contents')) {
    $result=call_user_func($over_func_name, $url);
}

function fileGetContents($url)
{
  /// statements
}

?>

 

PHP Function OverRide Class

<?php 


class override 
{ 

var $functions = array(); 
var $includes = array(); 

function override_function($override, $function, $include) { 
 if ($include) { 
 $this->includes[$override] = $include; 
 } 
 else if (isset($this->includes[$override])) { 
  unset($this->includes[$override]); 
 } 
 $this->functions[$override] = $function; 
} 


function override_check($override) { 
 if (isset($this->includes[$override])) { 
 if (file_exists($this->includes[$override])) { 
 include_once($this->includes[$override]); 
} 

if (function_exists($this->functions[$override])) {
 return $this->functions[$override]; 
} 
else 
{ 
 return false; 
} 
} 
else 
{ 
return false; 
} 
} 
} 

?>

Make a habit of creating things modular, that means “pluggable” and “unpluggable”.