有人告诉我在 PHP 中不能在类中定义类。然而,在我自己的例子中,这似乎有效,这让我感到困惑:
类_测试.php:
require('class_1.php');
new class_1
//Need $missing_variable here.
类_1.php
class class_1{
public function function_1(){
function callback_function(){
echo "A Callback";
$missing_variable = "Where Did I Go?";
}
require('class_2.php');
new class_2('callback_function');
}
public function __construct(){
$this->function_1();
}
}
类_2.php
class class_2{
public function __construct($callback){
echo "Hello World - ";
call_user_func($callback);
}
}
加载class_test.php打印出来
Hello World - A Callback
Question: 怎么定义$missing_variable
这样我就可以把它拿到我需要的地方?
如果将来有人遇到类似的问题,无论可能性如何,我想从下面链接到键盘,显示从类外部回显的 $missing_variable :
http://codepad.org/tRk0XWG7 http://codepad.org/tRk0XWG7
再次感谢大家。
Note: This is a follow up https://stackoverflow.com/questions/13468754/about-scope-and-oop-in-php.
您可以在 a 中声明一个类function。这就是所谓的有条件声明,即只有调用该函数时才会声明该类。无论你是否include
包含类声明的文件或者您在函数内键入代码。
然而,这并不意味着这些类共享任何类型的范围或数据。只有声明是有条件嵌套的,它仍然具有与之前解释过 https://stackoverflow.com/a/13469110/476.
您对回调的困惑可以用同样的事情来解释。什么时候class_1::function_1
第一次执行时,function callback_function
正在被定义。这是一个常规的全局函数,可以从任何地方调用。它不以任何方式绑定到类。您还会注意到您无法执行class_1::function_1
第二次,PHP 会抱怨callback_function
当您尝试再次声明它时它已经存在。
As for the comment in the source code //How do I declare this variable so that it is available where I need it?
: You don't. That variable is a local variable inside a function. It's only in scope inside the function. You can return
its value from the function like any other return value if you want to. (You could make it global
, but for the love of god don't!) If you need that value somewhere else, don't declare it as a variable inside a function, because only the function can access it then.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)