php override standard function

Is it possible to overwrite a function in PHP

Can you declare a function like this.

And then redeclare it somewhat like this.

Is it possible to overwrite a function that way?

php override standard function. Смотреть фото php override standard function. Смотреть картинку php override standard function. Картинка про php override standard function. Фото php override standard function

10 Answers 10

To address comments that this answer doesn’t directly address the original question. If you got here from a Google Search, start here

There is a function available called override_function that actually fits the bill. However, given that this function is part of The Advanced PHP Debugger extension, it’s hard to make an argument that override_function() is intended for production use. Therefore, I would say «No», it is not possible to overwrite a function with the intent that the original questioner had in mind.

Original Answer

This is where you should take advantage of OOP, specifically polymorphism.

Monkey patch in namespace php >= 5.3

A less evasive method than modifying the interpreter is the monkey patch.

Monkey patching is the art of replacing the actual implementation with a similar «patch» of your own.

Ninja skills

Before you can monkey patch like a PHP Ninja we first have to understand PHPs namespaces.

Since PHP 5.3 we got introduced to namespaces which you might at first glance denote to be equivalent to something like java packages perhaps, but it’s not quite the same. Namespaces, in PHP, is a way to encapsulate scope by creating a hierarchy of focus, especially for functions and constants. As this topic, fallback to global functions, aims to explain.

You will not be able to define a function print_r($object) <> in the global namespace because this will cause a name collision since a function with that name already exists.

Expect a fatal error to the likes of:

But nothing stops you, however, from doing just that within the scope of a namespace.

Patching the monkey

Say you have a script using several print_r(); calls.

Example:

But you later change your mind and you want the output wrapped in tags instead. Ever happened to you?

Before you go and change every call to print_r(); consider monkey patching instead.

Example:

Your script will now be using MyNamespace\print_r(); instead of the global \print_r();

Источник

What is function overloading and overriding in php?

In PHP, what do you mean by function overloading and function overriding. and what is the difference between both of them? couldn’t figure out what is the difference between them.

10 Answers 10

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.

An example of overriding:

php override standard function. Смотреть фото php override standard function. Смотреть картинку php override standard function. Картинка про php override standard function. Фото php override standard function

Function overloading occurs when you define the same function name twice (or more) using different set of parameters. For example:

In the example above, the function compute is overloaded with two different parameter signatures. *This is not yet supported in PHP. An alternative is to use optional arguments:

Function overriding occurs when you extend a class and rewrite a function which existed in the parent class:

Strictly speaking, there’s no difference, since you cannot do either 🙂

Function overriding could have been done with a PHP extension like APD, but it’s deprecated and afaik last version was unusable.

Function overloading in PHP cannot be done due to dynamic typing, ie, in PHP you don’t «define» variables to be a particular type. Example:

Each variable is of a different type, yet you can know the type before execution (see the 4th one). As a comparison, other languages use:

In the last example, you must forcefully set the variable’s type (as an example, I used data type «something»).

Another «issue» why function overloading is not possible in PHP: PHP has a function called func_get_args(), which returns an array of current arguments, now consider the following code:

Considering both functions accept any amount of arguments, which one should the compiler choose?

Finally, I’d like to point out why the above replies are partially wrong; function overloading/overriding is NOT equal to method overloading/overriding.

Where a method is like a function but specific to a class, in which case, PHP does allow overriding in classes, but again no overloading, due to language semantics.

To conclude, languages like Javascript allow overriding (but again, no overloading), however they may also show the difference between overriding a user function and a method:

Источник

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.

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:

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

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:

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

php override standard function. Смотреть фото php override standard function. Смотреть картинку php override standard function. Картинка про php override standard function. Фото php override standard function

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.

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

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:

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:

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:

php override standard function. Смотреть фото php override standard function. Смотреть картинку php override standard function. Картинка про php override standard function. Фото php override standard function

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:

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

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

Источник

Is it possible to override a default PHP function?

I would like to override the _() PHP function so that it supports one or more arguments. Is it possible to do that using PHP code?

4 Answers 4

No, but with PHP version >= 5.3.0 you could use namespacing though.

You could try the runkit extension but it’s considered a bad practice in production environments. See also Redefining PHP function?

It is possible, using the Runkit extension.

However, it’s generally not considered a good idea, except for use with things like unit testing, where you may want to isolate some of your functionality.

For general use, you shouldn’t be overriding built-in functions because it makes your code harder to maintain, and opens you up to some very hard to debug issues.

Also, the Runkit extension is marked as ‘experimental’, which means it really shouldn’t be used in a production system.

Really don’t do this! Even if you are the only developer on this project and know that your project won’t be successful, one can never know how long your code will be in use (often much longer than you would think). Should another developer have to dive into your code, he will have a very hard time, because he/she cannot rely on PHP itself.

A better way would be to write your own methods/functions, which then call the PHP function you want to overwrite. This way a developer immediately can see, that this is not the standard PHP function, and even if PHP will allow other parameters in future versions, you will have a clean solution.

Источник

Overriding methods in PHP?

Is there a way to do so in PHP? I mean, for example:

I want user to implement their own myClass::reImplementThis() method.

How can I do that in PHP? If it is possible, can I make it optional?

I mean, if the user is not implementing the method, can I specify a default method or can I identify that the method is not defined (can I do this using method_exists )?

php override standard function. Смотреть фото php override standard function. Смотреть картинку php override standard function. Картинка про php override standard function. Фото php override standard function

3 Answers 3

This way the class TestTest must override the function test.

This touches on several OOP subjects.

First, simply overriding an method declared in a parent class is as simple as re-declaring the method in an inheriting class.

If on the overriding method you wan to reuse the logic of the overriden one, it’s just a matter of calling the parent’s method from the extending class::

One thing to note is that overriding methods have to be compatible with the overriden one: the method visibility can’t be more restrictive than the original one (it’s OK to increase visibility), and the number and type of required arguments can’t conflict with the original delcaration.

This works, because the type of the arguments does not clash with the original, and we have less required arguments than on the parent:

But this doesn’t, since there are additional required arguments. This would make impossible to switch the original class for this one transparently, and thus would throw a Warning :

Additionally, you mention in your question that «this method should be overriden by the user». If you require client classes to actually implement the method, you have a couple of options:

Abstract classes & methods

These are methods where the implementation is left empty, and that extending classes have to implement to be valid. In we changed our original class Person to:

An example of a valid class extending Person now would be:

Any class that extends Person must declare a public hide() method.

Interfaces

Finally, you mention interfaces. Interfaces are contracts that implementing classes have to fulfill. They declare a group of public methods without an implementation body.

Now we could have class that extended Person and implemented Policeman :

Importantly, while it’s possible to extend only one class (there is no multiple inheritance in PHP), it is possible to implement multiple interfaces, and the requirements for each of those have to be fulfilled for the class to be valid.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *