4

When using the PHP CLI interpreter, how might one redefine a function that has a bug. For instance, the original function declaration here lacks a newline character and I would like to fix it:

$ php -a
Interactive shell

php > function drinkBeer(){
php {     echo "Carlsburg";
php { }
php > 
php > drinkBeer();
Carlsburgphp > 
php > 
php > function drinkBeer(){
php {     echo "Carlsburg" . PHP_EOL;
php { }
PHP Fatal error:  Cannot redeclare drinkBeer() (previously declared in php shell code:2) in php shell code on line 3
php >

We have seen similar questions asking how to redefine a function when running a PHP script however none of the similar questions address the issue of redefining functions on the PHP CLI interpreter.

For instance, the Python interpreter allows this:

$ python3

>>> def drinkBeer():
...  print('Carlsburg')
... 
>>> drinkBeer()
Carlsburg
>>>
>>> def drinkBeer():
...  print("You've had enough!")
... 
>>> drinkBeer()
You've had enough!
>>>
Community
  • 1
  • 1
dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • Why should the interpreter matter? The language is the same, you simply don't have access to HTTP stuff like `$_SERVER['HTTP_HOST']`. – Álvaro González Feb 24 '14 at 12:48
  • 1
    If you have the potential to make mistakes then dont use the `-a` option. Save the php code into a file eg `test.php` and run it like this `php test.php`. – RiggsFolly Feb 24 '14 at 12:54
  • Use UP and DOWN arrows to edit the previously inserted code. – Filipe YaBa Polido Feb 24 '14 at 12:58
  • @RiggsFolly: Considering that the potential to make mistakes is `E = 1/2 m v^2` and I have too much `m`, I make many mistakes! – dotancohen Feb 24 '14 at 13:15
  • We all do. I was not suggesting it was just you that makes mistakes, only that its easier to fix them if you dont have to code 100% script every time we do! – RiggsFolly Feb 24 '14 at 15:09
  • Notice how this question implicitly demonstrates the readability advantage of Python. – dotancohen Jun 27 '14 at 06:34

2 Answers2

4

If you are using PHP 5.3 or newer you can do the following

$func = function(){ echo "Foo"; };
$func(); //to execute
$func = function(){ echo "Bar"; };
$func(); // will echo Bar
Hazem Mohamed
  • 564
  • 3
  • 7
-2

See this for function oriented programming http://www.php.net/manual/en/function.override-function.php

Form object oriented, just declare function in child class and use it!

Hope it was helpfull...

Good luck!

Debster
  • 1
  • 1