Algorithms, Blockchain and Cloud

Bug-fixes for PHP Online Logo Interpreter


In December, 2006, I wrote a PHP Logo Interpreter [PHP Online Logo Interpreter]. At that time, PHP4 was widely used. Everything in PHP4 is passed by value. For example, if you need to duplicate an object, you can simply copy it by assigning to another variable. The workaround to pass by reference in PHP4 is to give an symbol & before variables. For example, the following illustrates the pass-by-reference and pass-by-value to function parameters in PHP4.

function test($a, &$b) {
    $b = 1;
    return ($a - 1);
  }
  
  $aa = 1;
  $bb = 0;
  echo test($aa, &$bb);    // in PHP4 , you need the "&" 
                           // but in PHP5 it is depreciated 

In PHP5, the above code will generate a warning:

PHP Warning:  Call-time pass-by-reference has been deprecated

The Logo Program, which draws a tree, using double recursion, is given below.

# Tree
to tree :size // with one parameter
  if (:size<10) [stop]
  fd :size
  lt 30 tree :size*0.7  ; left branch, recursive
  rt 60 tree :size*0.7  ; right branch, recursive
  lt 30 
  bk :size
end

bk 100 tree 100         ; draw a tree

See also: Teaching Kids Programming – Draw a Tree in Python using Turtle Graphics (Recursion)

It is supposed to draw a tree, like the following.

However, the Version 0.1 code works perfectly on PHP4 but not on PHP5 because later in 2008, the web-hosting company upgraded the PHP to PHP5 and the same PHP code produced the following.

This is weird, what happened? I went through most of the code line by line and figured out finally. The following was in PHP4 to copy parameters for new invoke of procedures (e.g. recursive calls).

$this->_var_stack[] = $this->_to_args[$procpos]; 

The PHP4 will duplicate the parameter object and push it to the stack, which is no problem. However, under PHP5, this has been passed as references, i.e. changing the value of the parameters in recursive procedures will affect its parental functions as well, which results unexpected output. To fix this bug is easy, simply add a keyword ‘clone‘ which tells PHP5 that this should be copied by values instead of references.

$this->_var_stack[] = clone $this->_to_args[$procpos]; 

–EOF (The Ultimate Computing & Technology Blog) —

508 words
Last Post: MSDOS .COM Assembly TV Colour Screen
Next Post: Console in Javascript

The Permanent URL is: Bug-fixes for PHP Online Logo Interpreter (AMP Version)

Exit mobile version