简体   繁体   中英

How to override built-in PHP function(s)?

I would like to override, let's say mysql_num_rows with let's say following:

$dataset = array(array('id' => 1, 'name' => 'Zlatan', 'onSOF' => 1), array('id' => 1, 'name' => 'Guest', 'onSOF' => 0));

function mysql_num_rows($dataset) {
    return sizeof($dataset);
}

Does PHP support built-in function overriding?


EXTENDING

I want to create an OpenSource solution which will override all existing mysql_* functions, and it their function body I'll be using PDO instances and methods, and properties.

This means that users who already use the mysql_* and find it hard to move completely to PDO, should just include this function override, and all properties, function calls, function return values, argument values, etc, should be left the same.

I think it could be done like so:

//First rename existing function
rename_function('strlen', 'new_strlen');
//Override function with another
override_function('strlen', '$string', 'return override_strlen($string);');

//Create the other function
function override_strlen($string){
        return new_strlen($string);  
}

found it here

Notice that every host must have http://php.net/manual/en/book.apd.php installed on the server.

Edit

Another way is to use namespaces

<?php
    namespace mysql2pdo;
    use PDO;
    function mysql_connect() {
       return new PDO();
    }
    echo mysql_connect(); // Causes error because we don't have the parameters
?>

Test it here

Install runkit & use runkit_function_redefine . Only do it on development/testservers, never in production.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM