PHP function use variable from outside

PhpFunctionVariables

Php Problem Overview


function parts($part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo($tructure . $part . '.php'); 
}

This function uses a variable $site_url that was defined at the top of this page, but this variable is not being passed into the function.

How do we get it to return in the function?

Php Solutions


Solution 1 - Php

Add second parameter

You need to pass additional parameter to your function:

function parts($site_url, $part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
}

In case of closures

If you'd rather use closures then you can import variable to the current scope (the use keyword):

$parts = function($part) use ($site_url) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
};

global - a bad practice

This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

For the completeness sake here is the solution using global:

function parts($part) { 
    global $site_url;
    $structure = 'http://' . $site_url . 'content/'; 
    echo($structure . $part . '.php'); 
}

It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).

Suggested reading:

Solution 2 - Php

Alternatively, you can bring variables in from the outside scope by using closures with the use keyword.

$myVar = "foo";
$myFunction = function($arg1, $arg2) use ($myVar)
{
 return $arg1 . $myVar . $arg2;
};

Solution 3 - Php

Do not forget that you also can pass these use variables by reference.

The use cases are when you need to change the use'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).

$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
	$newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);

Now $newarray will comprise (pseudocode here for brevity) [{times2:2},{times2:4}].

On the contrary, using $newarray with no & modifier would make outer $newarray variable be read-only accessible from within the closure scope. But $newarray within closure scope would be a completelly different newly created variable living only within the closure scope.

Despite both variables' names are the same these would be two different variables. The outer $newarray variable would comprise [] in this case after the code has finishes.

Solution 4 - Php

I suppose this depends on your architecture and whatever else you may need to consider, but you could also take the object-oriented approach and use a class.

class ClassName {

	private $site_url;

	function __construct( $url ) {
		$this->site_url = $url;
	}

	public function parts( string $part ) {
		echo 'http://' . $this->site_url . 'content/' . $part . '.php';
	}

	# You could build a bunch of other things here
	# too and still have access to $this->site_url.
}

Then you can create and use the object wherever you'd like.

$obj = new ClassName($site_url);
$obj->parts('part_argument');

This could be overkill for what OP was specifically trying to achieve, but it's at least an option I wanted to put on the table for newcomers since nobody mentioned it yet.

The advantage here is scalability and containment. For example, if you find yourself needing to pass the same variables as references to multiple functions for the sake of a common task, that could be an indicator that a class is in order.

Solution 5 - Php

I had similar question. Answer: use global. And there are other options. But if you need named function with usage of outside scope, here what I have:

global $myNamedFunctionWidelyAccessibleCallableWithScope;
$myNamedFunctionWidelyAccessibleCallableWithScope =
    function ($argument) use ($part, $orWhatYouWant) {
        echo($argument . $part . '.php');
        // do something here
        return $orWhatYouWant;
    };
function myNamedFunctionWidelyAccessible(string $argument)
{
    global $myNamedFunctionWidelyAccessibleCallableWithScope;
    return $myNamedFunctionWidelyAccessibleCallableWithScope($argument);
}

It is useful for making function myNamedFunctionWidelyAccessible accissible from everywhere, but also binds it with scope. And I deliberately gave very long name, global things are evil :(

Here is documentation with a good example

Solution 6 - Php

Just put in the function using GLOBAL keyword:

 global $site_url;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRIKView Question on Stackoverflow
Solution 1 - PhpZbigniewView Answer on Stackoverflow
Solution 2 - PhpJoe GreenView Answer on Stackoverflow
Solution 3 - PhpValentine ShiView Answer on Stackoverflow
Solution 4 - PhpLeon WilliamsView Answer on Stackoverflow
Solution 5 - PhpGrigoryView Answer on Stackoverflow
Solution 6 - PhpHBv6View Answer on Stackoverflow