Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

David Jarrin
PLUS
David Jarrin
Courses Plus Student 11,182 Points

php class variable scope

Ok here is my problem: I am trying to make multiple API requests and I have to make the request in different functions that are within a class like so:

class exampleClass {

function callFunction1 () {
   stuff that makes a call
   return json;
}

function printStuffOut() {
  $jsonStuff = $this->callFunction1();
  $$jsonStuff->{'result'}[0]->{'fieldName'};
}

function printStuffOut2() {
  $jsonStuff = $this->callFunction1();
  $jsonStuff->{'result'}[0]->{'fieldName'};
}

}

first question, am I making two separate API calls 2nd question if I am is there a way to store that API call information say in an array then use that array in all the other functions in my class?

James Preus Jr.
James Preus Jr.
Courses Plus Student 8,582 Points

For the second part of your question...

1st Idea:

You can create a function and format the results as an array and then return it. Then when you go to make your subsequent API calls, you can do something like this:

$api->anotherFunctionCall($returned_array);

Where $returned_array is the array generated by your previous API call, then you use $returned_array in every subsequent API call on a function that you want to use it on.

2nd Idea:

Can you maybe use the __construct() function as the function that will generate the of information array, so that any function you call on the class will now include the array due to the nature of the __construct() function.

Will either of those work for you? I hope that can help and that I'm not wrong.

David Jarrin
David Jarrin
Courses Plus Student 11,182 Points

yea that was sort of my idea, I think I make the call inside of the constructor then assign it to a variable..... then I think I need to pass that variable into each of the print functions? I'll let you know how it goes.

3 Answers

David Jarrin
PLUS
David Jarrin
Courses Plus Student 11,182 Points

it had to do with member properties, setting the variable to private with in the class then making the call (and in the call you assign it back to the variable) http://stackoverflow.com/questions/34538046/multiple-api-calls-in-a-class/34538899#34538899

James Preus Jr.
PLUS
James Preus Jr.
Courses Plus Student 8,582 Points

Please do. If you have an error, post it and I'll help you with trying to fix it.