Suffice
Suffice

Reputation: 39

PHP - Reverse of calling a function?

Having some trouble with this..

<?php

EG204_ExoSkel();

function EG204_ExoSkel() { 

    $to_be_end = 'Red';

    everything_loop();

}

function everything_loop() {

    echo $to_be_end;

}

?>

The code above will not echo Red, so I must be trying to use functions backwards. Might that be possible?

All that is in the Everything function is to be apart of different foreach loops.

Upvotes: 0

Views: 263

Answers (3)

genesis
genesis

Reputation: 50976

Try this one (send it as an argument)

<?php
EG204_ExoSkel();

function EG204_ExoSkel() {

    $to_be_end = 'Red';

    everything_loop($to_be_end);

}

function everything_loop($argument) {

    echo $argument;

}
?>

http://sandbox.phpcode.eu/g/3c1b6.php

Upvotes: 4

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

Try referencing $to_be_end as a global!

WARNING Global are bad practice Avoid

<?php

EG204_ExoSkel();

function EG204_ExoSkel() { 

global $to_be_end;

$to_be_end = 'Red';

everything_loop();

}

function everything_loop() {

global $to_be_end;

echo $to_be_end;

}

?>

Upvotes: 0

Veger
Veger

Reputation: 37905

You have scoping issues. The declaration of $to_be_end is only available in the EG204_ExoSkel function.

If you want to use it outside that function you should use global to make it globally available. And also add global in the other function (also to made use of the global variable). Resulting in this:

EG204_ExoSkel();

function EG204_ExoSkel() { 
  global $to_be_end;    
  $to_be_end = 'Red';
  everything_loop();

}

function everything_loop() {
  global $to_be_end;
  echo $to_be_end;
}

Note: using global is considered bad practice and tends to make a mess of your code (and even introduce hard to find bugs). A better solution (if possible in your real code) is to pass on the variable to the other function(s).

Upvotes: 0

Related Questions