Override functions in php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Override function Extension for PHP

License

kjdev/php-ext-override

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Override function Extension for PHP

Build Status

This extension allows overrides functions.

override_function — Overrides functions

bool override_function ( string $name , string $args , string $code [ , string $origin ] )

Overrides functions by replacing them in the symbol table.

  • name The function to override.
  • args The function arguments, as a comma separated string.
  • code The new code for the function.
  • origin Original function to rename.

Returns TRUE on success or FALSE on failure.

override_function('test', '$a,$b', 'echo "TEST"; return $a * $b;'); override_function('test', '$a,$b', 'echo "TEST"; return $a * $b;', 'origin_test'); 

About

Override function Extension for PHP

Источник

PHP Override Method

Summary: in this tutorial, you will learn about the PHP overriding method and how to apply it effectively in your script.

Introduction to the PHP overriding method

Method overriding allows a child class to provide a specific implementation of a method already provided by its parent class.

To override a method, you redefine that method in the child class with the same name, parameters, and return type.

The method in the parent class is called overridden method, while the method in the child class is known as the overriding method. The code in the overriding method overrides (or replaces) the code in the overridden method.

PHP will decide which method (overridden or overriding method) to call based on the object used to invoke the method.

  • If an object of the parent class invokes the method, PHP will execute the overridden method.
  • But if an object of the child class invokes the method, PHP will execute the overriding method.

Let’s take an example to understand method overriding better.

The following example defines the Robot class that has one public method greet() and the Android class that inherits the Robot class:

 class Robot < public function greet() < return 'Hello!'; > > class Android extends Robot  Code language: HTML, XML (xml)

When you call the greet() method via the Android’s instance, PHP calls the greet() method of the Robot class:

 $android = new Android(); echo $android->greet(); // Hello!Code language: HTML, XML (xml)

This is a typical inheritance scenario.

Sometimes, you want to completely replace the method’s behavior of the parent class with a new one. In this case, you need to override the method of the parent class.

To override a method, you redefine the method in the parent class again in the child class but use a different logic.

The following adds the greet() method to the Android class that returns a different greeting message:

 class Robot < public function greet() < return 'Hello!'; > > class Android extends Robot < public function greet() < return 'Hi'; > > $robot = new Robot(); echo $robot->greet(); // Hello $android = new Android(); echo $android->greet(); // Hi!Code language: HTML, XML (xml)
  • First, invoke the greet() method of an instance of the Robot class, the greet() method in the Robot class executes.
  • Second, call the greet() method of an instance of the Android class, the greet() method in the Android class executes.

The following class diagram illustrates the relationship between the Robot and Android classes:

Call the overridden method in the overriding method

When you override a method, you will have two versions of the same method: one in the parent class and the other in the child class.

If you call the method of the parent class in the method in the child class, you cannot use $this keyword like this:

 class Android extends Robot < public function greet() < $greeting = $this->greet(); return $greeting . ' from Android.'; > >Code language: HTML, XML (xml)

The $this->greet() will call itself indefinitely.

To call the greet() method of the Robot class, you need to use the parent with the scope resolution operator (:: ) like the following:

 class Android extends Robot < public function greet() < $greeting = parent::greet(); return $greeting . ' from Android.'; > >Code language: HTML, XML (xml)

In this example, the greet() method in the Andoird class calls the greet() method of the Robot class. It concatenates the string returned by the greet() method of the Robot method with a literal string ‘ from Android.’ and returns the concatenated string.

More on PHP overriding method

Suppose that you need to define a new CheckingAccount class that extends the BankAccount class. The following defines the BankAccount class:

 class BankAccount < private $balance; public function __construct($amount) < $this->balance = $amount; > public function getBalance() < return $this->balance; > public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > return $this; > public function withdraw($amount) < if ($amount > 0 && $amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: HTML, XML (xml)

The withdraw() method checks if the withdrawal amount is greater than zero and less than or equal to the current balance before deducting it from the balance.

Second, define the CheckingAccount class that inherits the BankAccount class. The CheckingAccount class also has the withdraw() method that overrides the withdraw() method of the BankAccount class:

 class CheckingAccount extends BankAccount < private $minBalance; public function __construct($amount, $minBalance) < if ($amount > 0 && $amount >= $minBalance) < parent::__construct($amount); $this->minBalance = $minBalance; > else < throw new InvalidArgumentException('amount must be more than zero and higher than the minimum balance'); > > public function withdraw($amount)  < $canWithdraw = $amount >0 && $this->getBalance() - $amount > $this->minBalance; if ($canWithdraw) < parent::withdraw($amount); return true; > return false; > >Code language: HTML, XML (xml)

The withdraw() method in the CheckingAccount class checks the withdrawal amount against the minimum balance before deducting it.

The following class diagram illustrates the relationship between the BankAccount and CheckingAccount classes:

The final method

To prevent the method in the child class from overriding the method in the parent class, you can prefix the method with the final keyword:

public final function methodName() < //. >Code language: PHP (php)

The following adds the id() method to the Robot class:

class Robot < public function greet() < return 'Hello!'; > final public function id() < return uniqid(); > >Code language: PHP (php)

If you attempt to override the id() method from the Android class, you’ll get an error. For example:

class Android extends Robot < public function greet() < $greeting = parent::greet(); return $greeting . ' from Andoid.'; > public function id() < return uniqid('Android-'); > >Code language: PHP (php)
Cannot override final method Robot::id()Code language: PHP (php)

Summary

  • Method overriding allows a child class to define a method that overrides (or replaces) the method already provided by its parent class.
  • Use parent:: to call the overridden method in the overriding method.
  • Use the final method when you don’t want a child class’s method to override a parent class’s method.

Источник

override_function

Overrides built-in functions by replacing them in the symbol table.

Parameters

The function arguments, as a comma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \ $your_var .

The new code for the function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 override_function() example

User Contributed Notes 8 notes

I thought the example was not very helpful, because it doesn’t even override the function with another function.
My question was: If I override a function, can I call the ORIGINAL function within the OVERRIDING function?
ie, can I do this:
override_function ( ‘strlen’ , ‘$string’ , ‘return override_strlen($string);’ );
function override_strlen ( $string ) return strlen ( $string );
>
?>
The answer: NO, you will get a segfault.

HOWEVER, if you use rename_function to rename the original function to a third name, then call the third name in the OVERRIDING function, you will get the desired effect:
rename_function ( ‘strlen’ , ‘new_strlen’ );
override_function ( ‘strlen’ , ‘$string’ , ‘return override_strlen($string);’ );

function override_strlen ( $string ) return new_strlen ( $string );
>
?>

I plan to use this functionality to generate log reports every time a function is called, with the parameters, time, result, etc. So to wrap a function in logging, that was what I had to do.

Overriden function name becomes __overridden__(). That’s why you can’t override two function, and that’s how you can use the original function in the override.

Of course you can’t overwrite «functions» like require_once or print as they are not really a function but a language construct.

Please note that this function (as of v1.0.1 in PHP 5.3) will not override some important built-in «functions». Specifically, those which are actually statements/keywords, such as:

require
include
require_once
include_once
echo
print

I was hoping to use it to trace the chains of require/include activity among files in a large legacy project, but it seems APD will not do what I need.

Yes you can if you rename the overridden function. So you first rename original function, then override it and finally rename the overridden one, something like this:

rename_function(‘feof’, ‘real_feof’);
override_function(‘feof’, ‘$handle’, ‘return true;’);
rename_function(«__overridden__», ‘dummy_feof’);

You can find Excepción — Call to undefined function override_function()
due to Function override_function is part of PECL Extension.

There is not chance to override 2 or more functions, because of the error:
Fatal error: Cannot redeclare __overridden__()

Maybe it’s better to use overwritten function inside the override to code something like this :
rename_function ( ‘myFunction’ , ‘original_myFunction’ );
override_function ( ‘myFunction’ , ‘$arg,…,$argN’ , ‘return override_myFunction($arg,…,$argN);’ );
?>

You may then give somehow «inheritance» to override_myFunction …
As a parent :
function override_myFunction ( $arg , … , $argN )
< $result = original_myFunction ( $arg , … , $argN ));
/* CODE that manipulates the result */
return $result ;
>
?>

As a child :
function override_myFunction ( $arg , … , $argN )
< /* CODE that manipulates the arguments */
return original_myFunction ( $arg , … , $argN ));
>
?>

Оцените статью