Using global PHP variables inside a class in CF?

yorb 19 Jan, 2011
...I can't get it to work.😟

<?php

$test = 'Success!';
class TestClass {
	public function __construct() {
		global $test;
		echo "var: " . $test;
	}
}
$dummyInstance = new TestClass();


?>


This should output:

var: Success!



...And if you drop the code above into a PHP file and load it up in a browser, you will see that output. But if you drop that same code into a box in CF, you just get:

var:



Form HTML, On submit before, On submit after, doesn't seem to matter. Same output. Took me a while to drill down and isolate this problem. I don't know if it's a CF bug or a J! bug (or some sort of "security feature"πŸ˜›), but I'm wondering if anyone has a workaround. I'll keep trying things.

FYI, I need this functionality because I'm trying to define variables for a file that I will include, containing a big ol' API wrapper class. In CF, I can't get the wrapper class to see the variables.

Ideas?

Thanks!
GreyHead 19 Jan, 2011
Hi yorb,

Try:
<?php
global $test;
$test = 'Success!';
class TestClass {
   public function __construct() {
      global $test;
      echo "var: " . $test;
   }
}
$dummyInstance = new TestClass();
?>

Bob
yorb 19 Jan, 2011
Thanks, I JUST figured that out haha. Feel free to delete the thread if you find it silly and useless.πŸ˜€

It occurred to me to try it inside a regular function, and when THAT didn't work I knew something was up. Declaring it global before the definition fixed it. Why does CF require that? Or rather, why can I get away without using it outside of CF?
GreyHead 20 Jan, 2011
Hi yorb,

It's because the ChronoForms boxes are called using eval() and not include() so they don't have global scope. As long as you define a variable as global before it is used then you can do this. I think it will also work between boxes as well for the OnSubmit code.

Bob
This topic is locked and no more replies can be posted.