PHP中如何在一个函数中获取另一个函数的值?附代码求解
Hey there! Let's sort out this variable scope problem in your code right away. The issue here is that $name is a local variable inside function a()—it only lives within that function's scope, so function b() can't reach it directly. Here are three practical ways to make this work, ordered by best practice:
1. Return the Value and Pass It as a Parameter (Recommended)
This is the cleanest, most maintainable approach—explicitly passing values between functions makes your code easy to follow:
function a() { $name = "hello world"; return $name; // Return the variable's value from function a } function b($name) { echo $name; // Use the passed parameter } // How to call them: $retrievedName = a(); b($retrievedName); // Outputs "hello world"
2. Use Global Variables (Not Recommended)
While this works, global variables can make your code hard to debug and scale—they create hidden dependencies between functions. But here's how it would look:
function a() { global $name; // Declare that we're using the global $name variable $name = "hello world"; } function b() { global $name; // Access the same global variable echo $name; } // How to call them: a(); b(); // Outputs "hello world"
3. Use a Closure (For Specific Scenarios)
If you need to encapsulate the logic of b() while retaining access to a()'s variable, a closure (anonymous function) works well:
function a() { $name = "hello world"; // Return a closure that "captures" the $name variable return function() use ($name) { echo $name; }; } // How to call them: $printName = a(); $printName(); // Outputs "hello world"
Final Note
Stick with the first method whenever possible—it aligns with PHP best practices, keeps your code predictable, and avoids the pitfalls of global variables.
内容的提问来源于stack exchange,提问作者Sathish

