Can you declare a function like this...
function ihatefooexamples(){ return "boo-foo!"; };
And then redeclare it somewhat like this...
if ($_GET['foolevel'] == 10){ function ihatefooexamples(){ return "really boo-foo"; }; };
Is it possible to overwrite a function that way?
Any way?
Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments.
This is not possible in PHP, one need to test the parameter types yourself, or write several functions.
PHP is a Loosely Typed LanguageIn PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type mismatches.
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.
This is where you should take advantage of OOP, specifically polymorphism.
interface Fooable { public function ihatefooexamples(); } class Foo implements Fooable { public function ihatefooexamples() { return "boo-foo!"; } } class FooBar implements Fooable { public function ihatefooexamples() { return "really boo-foo"; } } $foo = new Foo(); if (10 == $_GET['foolevel']) { $foo = new FooBar(); } echo $foo->ihatefooexamples();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With