Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Oct 5 Previous

Just take a rope, that's easier

Consider the following PHP script:


$diameter = 20;
$circumference = 0;

function circumference() {


echo $circumference;


What should be placed at the dots to get (a proper estimate of) the circumference of a circle of 20 px, pt, ex, sea miles, cows or whatever printed in your browser window?

A: global $diameter; return $circumference = $diameter * 3.14;
B: $circumference = $diameter * 3.14;
C: global $circumference; $circumference = $diameter * 3.14;
D: $GLOBAL["circumference"] = $GLOBAL["diameter"] * 3.14;

Check all that apply.


If you want this to work you'll need a way to access the global variables $diameter and $circumference from within the function calculate(). This can be done by the keyword global or through the $GLOBAL array.

So answer B is false: the variables $diameter and $circumference will not be known to the function.

Anwer A is tricky: it will calcuate the circumference and store it in variable $circumference. However this version of $circumference is known to the function only and will not affect the global one because only $diameter was listed as global variabe. The function correctly returns the value of the circumference but its value was not assigned to the global variable $circumference in line 10. So answer A is not correct.

Something alike applies to answer C. This would have worked if $circumference and $diameter were both listed as global. Only $diameter is, so this answer is false too.

In answer D the $GLOBALS array was used to alter the value of the $circumference variable and this will work, so answer D is true.

Note that using globals in a situation like this (if not any situation) is considered very bad programming. If however you choose/need to use global variables in your function please treat them as constants and do not alter their values from within a function as was attempted in this example: your fellow programmers will be very grateful.