Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overwrite a function in PHP

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?

like image 989
Mark Lalor Avatar asked Sep 01 '10 17:09

Mark Lalor


People also ask

Is overriding possible in PHP?

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.

Can we have two functions with the same name in PHP?

This is not possible in PHP, one need to test the parameter types yourself, or write several functions.

Can we declare function in PHP?

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.


1 Answers

Edit

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.

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(); 
like image 133
Peter Bailey Avatar answered Sep 21 '22 23:09

Peter Bailey