Variable usage outside the function where they were extracted

I have an array with associated keys that point to instantiated objects. For example:

$MyArray = array();
$MyArray['Object_A'] = new Object_A();
$MyArray['Object_B'] = new Object_B();
$MyArray['Object_C'] = new Object_C();

What I would like to do with this array is to extract it to variables as references to those objects.

extract($MyArray, EXTR_REFS);

The statement works and I am able to use those objects inside that array just as I would do $Var = new Object();.

$Object_A->SomeMethod();

However when I extract them in a function that I define they can no longer be used outside that function. They can be used inside the function like the example below but not outside.

function ExtractObj(&$Array)
{
    extract($Array, EXTR_REFS);

    $Object_A->SomeMethod(); // This works.
}

So I need a way to make the extracted variables from that function to be usable from outside the function.

function ExtractObj(&$Array)
{
    extract($Array, EXTR_REFS);
}

$Object_A->SomeMethod(); // Not working (Yet).

NOTE: I have tried to use global, static variable modifiers or methods and so on but everything gives me an error.

Answers


Yes, you are correct. Variables have function scope, so they are not available outside the function. Learn to pass variables into a function as parameters, return needed values from the function and live with the function scope, it will make your programs better and more maintainable than one big messy global scope.


Need Your Help

During prepareForSegue get [UIViewController <null selector>] when try to assign value to property?

objective-c ios exception segue

during the prepareForSegue I try to assign a value to property and get the error

Create new StringBuilder by looping through list, remove last element

c# .net vb.net stringbuilder

I know this might be a bad example, but my question in this case has more to do with the best / most efficient way to deal with a StringBuilder rather than my SQL query itself, so please bear with ...