php require方法中的类调用 [英] php require class call from inside method
问题描述
从我的理解,需要粘贴代码到调用php文件。
from my understanding, require pastes code into the calling php file.
如果你要求从一个方法...它会粘贴整个代码/
what if you were requiring from inside a method...it would paste the entire code/class inside the method, blocking the next statement in the method.
例如
function test() {
require 'pathtosomeclasscode';
somestatement; // any code after the require is blocked.
}
如何解决这个问题,
推荐答案
有些令人惊讶的是,这似乎工作得很好。所包含的代码将在Baz :: bork()的范围内执行 - 但是代码只是定义了一个类,而类是全局的。
Somewhat surprisingly, this appears to work just fine. The included code will execute inside the scope of Baz::bork() -- but the the code simply defines a class, and classes are global. So you end up with a defined class.
文件:Foo.php:
File: Foo.php:
<?PHP
class Foo{
function bar(){
echo "Hello from Foo::bar()!\n";
}
}
档案:Baz.php:
File: Baz.php:
<?PHP
class Baz{
function bork(){
require_once "Foo.php";
$f = new Foo();
$f->bar();
}
}
echo "testing internal definition:\n";
$b = new Baz();
$b->bork();
echo "\ntesting in global scope:\n";
$f = new Foo();
$f->bar();
echo "\nall done\n";
输出:
$ php Baz.php
testing internal definition:
Hello from Foo::bar()!
testing in global scope:
Hello from Foo::bar()!
all done
现在,我想不到很多地方你会想这样做的事情。人们通常在类定义之外的类文件的顶部require_once()任何可能的依赖。
Now, I can't think of many places where you'd want to do things this way. People typically require_once() any possible dependencies at the top of their class file, outside of the class definition.
这篇关于php require方法中的类调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!