2

How can I use class instance inside independent method? I some file have:

global $l;
$l = new l('bg');
include('second.php');

In second.php I have:

function a() {
    print_r($l);
}

$l is coming like NULL;

class l declaration:

class l {
    var $lang = array();
    function l($lang) {
    }
    function g($string) {
    }
}

My question - how can I use $l instance inside of my function a. Thanks.

2
  • $l is not in scope, global $l would work, but you could also pass it to the function as a parameter (better). Commented Mar 3, 2014 at 16:39
  • why passing as parameter is better solution? Thanks Commented Mar 3, 2014 at 16:47

1 Answer 1

3

In function a $l is not defined.

Either you pass it in as a parameter or you use global.

function a($l) {
    print_r($l);
}

global is not like var. It does not define a variable to be used as a global. Instead, global allows you to pull variables from the global scope, like:

$l = new l();
function a() {
    global $l;
    print_r($l);
}

I should also add that the use of global is heavily frowned upon, it breaks dependency expectations. This means that if you look at your function a you can't see that it needs $l. If it's a parameter then you know it needs $l.

Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely fabulous! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.