Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function use variable from outside

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?

like image 525
RIK Avatar asked Jun 18 '12 16:06

RIK


People also ask

How can a variable used outside a function be accessed by the function in PHP?

To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the function.

How do you access a variable outside a function?

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.


1 Answers

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:

  • Variable scope in PHP
  • Anonymous functions
like image 117
Zbigniew Avatar answered Sep 18 '22 06:09

Zbigniew