0

What is the best approach to accessing a variable out of scope, see my current method:

// Define API
require_once( 'api.php' );
global $myapi;
$myapi = new LazyAPI( 'My API', 'myapi' );

class Content {

    function DoAction() {

        global $myapi;
        $key = $myapi->someFunc() . "-key";

    }

}

$content = $myapi->Content(); // LazyAPI is a class that loads classes in other files using reflection
$content->DoAction();

The issue I am facing (and am unable to test until further on) is redeclaring or reusing $myapi in other files. I have only used the global access modifer because I know it works, and I don't know if there is a better alternative. The idea is to be able to declare multiple $myapi variables and only accessible within the scope of the main file.

Nahydrin
  • 13,197
  • 12
  • 59
  • 101
  • Correct me if I'm wrong. But couldn't you just do `require_once()` at the top and instantiate the api inside the function `DoAction()`? – Tuan Apr 25 '13 at 00:57
  • The `$myapi` is used in multiple classes. – Nahydrin Apr 25 '13 at 00:58
  • I think you are looking for the singleton pattern. Create a factory class that returns the same instance of `$myapi` wherever you need it. – Tuan Apr 25 '13 at 01:01
  • The variable can't always be the same, but the name always needs to be the same. Making it static/etc. wouldn't work. – Nahydrin Apr 25 '13 at 01:06

1 Answers1

1

Use depency injection

require_once( 'api.php' );

class Content {

    public function __construct($myapi) {
        $this->myapi = $myapi;
    }

    function DoAction() {
        $key = $this->myapi->someFunc() . "-key";
    }

}

$myapi = new LazyAPI('My API', 'myapi' );
$content = new Content($myapi);
$content->DoAction();

Some helpful slides about depency injection in PHP.

sectus
  • 15,605
  • 5
  • 55
  • 97
  • The variable `$myapi` needs to be a variable, as it's used in several classes. I know of passing the variable by constructor, but is there no better way? – Nahydrin Apr 25 '13 at 01:00
  • I should also point out something that makes this solution look "wrong" for me, please see the original post. – Nahydrin Apr 25 '13 at 01:03
  • @BrianGraham, with this way your class become testable, reusable, flexible... Yes, it's the best way. – sectus Apr 25 '13 at 01:05
  • See how I actually declare a new class? `$content = $myapi->Content();`. That's why `$content = $myapi->Content($myapi);` looks wrong and I don't want to use it. – Nahydrin Apr 25 '13 at 01:07
  • @BrianGraham, you can also use Factory. – sectus Apr 25 '13 at 01:07
  • @BrianGraham, great, you've changed dependency. – sectus Apr 25 '13 at 01:09
  • All the classes loaded by `LazyAPI` depend on `LazyAPI`, and it's designed to be user friendly on the frontend. – Nahydrin Apr 25 '13 at 01:10