简体   繁体   English

从PHP中的其他函数调用函数

[英]Calling functions from other functions in PHP

Hey so I got tired of writing 嘿,所以我厌倦了写作

echo "varname message";
var_dump(variable);

So I wrote this 所以我写了这个

function debugger($var, $message) {
    echo $message;
    var_dump($var);
    echo "<br />";
}

Which seems to work fine, except when its in a function. 似乎工作正常,除非在功能中。 Then its like it doesn't know that there's a function defined, because its defined outside of the function. 然后就好像它不知道定义了一个函数,因为它在函数外部定义。 Like so. 像这样

function blah() {
    $x = 2;
    debugger($x, "this is x");
}

Also, I don't understand functions, I knew you cant reference something in a function outside of the function without returning it, but I didn't know you couldn't reference variables or functions outside of the function without setting them as parameters. 另外,我不理解函数,我知道您不能在函数外部引用某个函数而不返回它,但我不知道您不能在不将变量或函数设置为参数的情况下引用该函数之外的变量或函数。 I think I have this wrong though. 我想我错了。

So one more thing, does that mean that the variables inside of a function don't conflict with the ones outside a function unless its returned? 那么还有另一件事,这是否意味着函数内部的变量与函数外部的变量除非返回就不会冲突?

Your code should work. 您的代码应该可以工作。 Something else is wrong in your code. 您的代码中有其他错误。 Try being more precise about what is not working and try isolating your problem. 尝试更精确地了解什么不起作用,然后尝试找出问题所在。 As for your other questions: 至于您的其他问题:

Variables defined in a function are scoped to that function, and will not interfere with variables from other functions. 函数中定义的变量的作用域是该函数,并且不会干扰其他函数的变量。 They also cannot access variables defined outside the function. 他们也不能访问在函数外部定义的变量。 For example 例如

$a = 5;
function foo() {
    echo $a; //This will not work
}

What you can do is use the global keyword to "include" variables into your function's scope, if you don't want to pass them as arguments: 如果您不想将变量作为参数传递,则可以使用global关键字将变量“包含”到函数的作用域中:

$a = 5;
function foo() {
    global $a;
    echo $a;
}

Or since a certain version of PHP (not sure which, if anyone knows please edit), you can use use : 或由于特定版本的PHP(不确定哪个版本,如果有人知道,请编辑),则可以使用use

$a = 5;
function foo() use ($a) {
    echo $a;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM