developerdave Posted July 20, 2010 Share Posted July 20, 2010 Well i've scoured the PHP.net documentation and Google'd this thoroughly and can't find anything, which suggests it is impossible but I thought I should get a collective opinion on it. So we all know what preg_match() is, its third argument (in most examples is $matches) becomes available to the rest of the script calling that function. What I want to be able to do is say I have a function called foo with the argument $bar I want the variable $bar to become available throughout the rest of my script. Like below. //I don't want to have to do this function foo() { return 'Foobar!'; } $bar = foo();//outputs Foobar! //but rather do this function foo($bar) { return $bar = 'Foobar!'; } echo $bar;//I want it to output Foobar! but doesn't I've tried quite a few thigns now and can't seem to work it out naturally, anyone have any suggestions? Quote Link to comment https://forums.phpfreaks.com/topic/208326-preg_match-like-global-variable-possible/ Share on other sites More sharing options...
AbraCadaver Posted July 20, 2010 Share Posted July 20, 2010 Pass by reference: function foo(&$bar) { $bar = 'Foobar!'; } $bar = 'Bar'; foo($bar); echo $bar; Quote Link to comment https://forums.phpfreaks.com/topic/208326-preg_match-like-global-variable-possible/#findComment-1088740 Share on other sites More sharing options...
AbraCadaver Posted July 20, 2010 Share Posted July 20, 2010 Just to clarify, you don't have to use the same var names inside and outside the function: function foo(&$bar) { $bar = 'Foobar!'; } $X = 'Bar'; foo($X); echo $X; //or echo foo($X); Quote Link to comment https://forums.phpfreaks.com/topic/208326-preg_match-like-global-variable-possible/#findComment-1088744 Share on other sites More sharing options...
developerdave Posted July 20, 2010 Author Share Posted July 20, 2010 Ooops my bad, this was simple :s Basically (just to explain) the function assigning the variable is member of a class which is instantiated by another class and returned (for method chaining) and this seemed like a good feature to have so the method chaining wasn't made redundant by having to separate lines for variable assignment. I set the inner class to accept by reference but not the controller All fixed now Thanks anyways guys Quote Link to comment https://forums.phpfreaks.com/topic/208326-preg_match-like-global-variable-possible/#findComment-1088748 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.