0

Previously, I had a global array ($v) and referenced it from within functions by using global $v;. I now want to encapsulate everything about that array, so I wrote a class. In the global context, I instantiate the class:

$vi = new my_v();

Within a function I want to call a method of that object:

function f($x) {
  $vi->add($x);
}

How do I refer to $vi within the function?

Will Fastie
  • 120
  • 1
  • 1
  • 9
  • 1
    possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – deceze Nov 25 '13 at 15:09
  • By the way, I know the class is good because calls to the add() method in the global scope work just fine. – Will Fastie Nov 25 '13 at 15:18
  • I'm embarrassed to say that the error being thrown was the result of a side effect. Global $vi does, indeed, work. – Will Fastie Nov 26 '13 at 03:42

1 Answers1

1

Use the global keyword:

function f($x) {
  global $vi;
  $vi->add($x);
}

You can also use the $GLOBALS superglobal array:

function f($x) {
  $GLOBALS['vi']->add($x);
}

See: http://us1.php.net/manual/en/language.variables.scope.php

Working example: http://3v4l.org/ERIK8

jszobody
  • 28,495
  • 6
  • 61
  • 72
  • That's what I thought, but PHP (5.2.17) is giving me **Fatal error: Call to a member function add() on a non-object in...** – Will Fastie Nov 25 '13 at 15:16
  • @WillFastie Sounds like your class isn't properly setup. Setup a really simple test case with no other code in the way. – jszobody Nov 25 '13 at 15:18
  • @WillFastie You can see both of those options in this working example: http://3v4l.org/ERIK8. If it's not working for you, you have some other issue going on with your code. – jszobody Nov 25 '13 at 15:20
  • I appreciate the tip about 3v4l.org. The code works there but not at my site, so you're right that there is some other issue. But it must be a scoping issue because the class works correctly in the global scope, just not when referenced from the local scope. – Will Fastie Nov 25 '13 at 16:07
  • @jszbody [link](http://3v4l.org/feUiN), exactly my code but with fewer items in the version array. Works at 3v4l but not at the site. – Will Fastie Nov 25 '13 at 16:22
  • @WillFastie I'm assuming you're running PHP 5.x and not a really old version? If the codes works on 3v4l, it's really hard to know why it's failing on your server, I'd be shooting in the dark. – jszobody Nov 25 '13 at 16:30
  • @WillFastie Are you using any php includes that define your variables, anything like that which could complicate things? – jszobody Nov 25 '13 at 16:32
  • @jszbody 5.2.17; no conflicts with other code (I searched the entire system looking for that and then renamed the class as a second test). No worries; at least I know I'm not crazy now. – Will Fastie Nov 25 '13 at 18:51