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?
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.
Just put in the function using GLOBAL keyword:
global $site_url;
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.
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;
};
Source: Stackoverflow.com