PHP function use variable from outside

PHP function use variable from outside

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP Function Variable Scope: Accessing External Variables Correctly

In the provided code snippet, the function parts attempts to construct a URL using $site_url. However, this variable is defined outside the function scope, likely at the top of the script or within a global namespace. The core issue here is variable scope. In PHP, variables defined in one scope are not automatically available inside functions unless explicitly passed or declared as global.

When you run the code as written, $site_url inside the parts function will be undefined, triggering a "Undefined variable" error (in strict mode) or returning an empty string if error reporting is off. This happens because PHP treats functions as encapsulated environments by default to prevent unintended side effects and maintain data integrity.

To resolve this, you must decide how to bridge the gap between the outer scope and the function's internal logic. There are three primary approaches, each with distinct implications for code architecture and maintainability.

Passing Variables as Arguments

The most robust and idiomatic solution in PHP is to pass the variable as an argument when calling the function. This approach enforces explicit dependency injection, making it clear exactly what data the function requires.

$site_url = 'example.com';

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

$result = parts('index', $site_url);

By adding $site_url to the function signature, you decouple the function from any global state. This is generally preferred because it prevents functions from relying on variables that might change unexpectedly elsewhere in the application. If $site_url changes, you only need to update the call site, not the function definition. Additionally, using return instead of echo allows the result to be reused or stored, which aligns with modern functional programming practices in PHP.

Declaring Global Variables

If modifying the call sites is not feasible and the variable must remain global, you can declare it inside the function using the global keyword.

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

While this solves the immediate problem, it introduces global coupling. The function now implicitly depends on a variable that exists anywhere in the script. This can lead to bugs where two different parts of your application try to set $site_url to different values simultaneously, causing unpredictable behavior. Furthermore, global variables make unit testing difficult because you have to mock or manipulate global state before running tests.

Using Static Properties (Optional Context)

Another pattern, often seen in legacy PHP applications, is using a static property within the function itself:

function parts($part) { 
    if (!isset(self::$site_url)) {
        self::$site_url = 'http://'; // Or fetch from config
    }
    $structure = self::$site_url . '/content/'; 
    return $structure . $part . '.php'; 
}

// Usage:
$site_url = 'example.com';
parts('index', $site_url); // Note: static doesn't auto-read global without assignment

However, this specific pattern requires manual assignment of the global variable to the static property before use, which defeats the purpose if you want pure automatic access. If your goal is simply to read a global variable defined at the top of the page, the global keyword or argument passing are the only direct methods.

Best Practices for URL Construction

Beyond scope issues, the code snippet has a minor but important syntax error in the original example: $tructure should be $structure. Additionally, hardcoding 'http://' is often less flexible than using the https:// scheme determined by your application's context or server configuration.

In larger applications, relying on global variables for configuration like base URLs is generally discouraged. Frameworks like Laravel handle this elegantly through dependency injection and service containers. If you are building a modern application, consider defining base URLs in a configuration file (e.g., config/app.php) or using the framework's helper functions, which abstract away these global state issues entirely.

Ultimately, passing variables as arguments is the standard for clean, testable code. It shifts the burden of data management to the caller, ensuring that the function behaves consistently regardless of where it is invoked in your codebase.

Our network