EllisLab text mark
Advanced Search
     
using PHP global variable in a function
Posted: 31 May 2012 07:35 PM   [ Ignore ]
Avatar
Joined: 2007-07-31
451 posts

It might be the lack of sleep but… This is not supposed to work?

I’ve never had to actually write my own function in EE so I might be missing something super obvious… but I’m doing something a little complicated and need to get this working. I’ve simplified the test to the max… Thanks!

<?php
$t 
"test";
function 
testing() {
 
global $t;
 if (isset(
$t)) {
  
echo "yep";
 
else {
  
echo "nope";
 
}
}
?>

<?testing
();?> 

This echoes “nope” ...

The real case scenario is a function to which I need to pass some EE template tags as arguments…

 Signature 

——————————————————-
Perfection is not when there is nothing to add, but when there is nothing to take away.

 
Posted: 01 June 2012 09:13 AM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2007-07-31
451 posts

I’ve passed the global as an argument as a workaround, like

<?testing($t);?> 

But that means I have to process $t every time in the function instead of once… I hope there’s some obvious way of doing what I need and that I’m just too dumb to know about it ;)

Thanks!

 Signature 

——————————————————-
Perfection is not when there is nothing to add, but when there is nothing to take away.

 
Posted: 27 July 2012 10:31 AM   [ Ignore ]   [ # 2 ]   [ Rating: 0 ]
Joined: 2011-07-01
13 posts

I have just had the same problem. The file I am running is set to PHP on Input.

 
Posted: 27 July 2012 11:02 AM   [ Ignore ]   [ # 3 ]   [ Rating: 0 ]
Joined: 2011-07-01
13 posts

Found the solution at

http://stackoverflow.com/questions/3193774/php-global-variable-is-undefined-inside-a-function-even-if-global-keyword-is-use

Apparently you have to use $GLOBALS so ...

$GLOBALS[‘xxx’] = array(“1”,“2”);
a();
b();
function a()
{
  global $xxx;
  array_push($xxx,“S”);
}
function b()
{
  global $xxx;
  echo($xxx[2]);
}

will echo out “S”.

 
Posted: 27 July 2012 03:47 PM   [ Ignore ]   [ # 4 ]   [ Rating: 0 ]
Avatar
Joined: 2007-07-31
451 posts

Thanks for posting back here :)

 Signature 

——————————————————-
Perfection is not when there is nothing to add, but when there is nothing to take away.