问题描述
您可以声明这样的函数...
pre $函数ihatefooexamples(){
返回boo-foo!;
};
然后 redeclare 有点像这样...
if($ _GET ['foolevel'] == 10){
function ihatefooexamples(){
returnreally BOO-foo的;
};
};
是否可以用这种方式覆盖函数?
$ b $ $ b
要解决评论,这个答案不直接解决
原来的问题。如果您是通过Google搜索获得的,请从这里开始
有一个可用的函数叫做,它实际上符合法案。但是,鉴于此功能是扩展的一部分,这很难使 override_function()
用于生产使用的论点。因此,我会说不,不可能用原始提问者的想法覆盖函数。
原始答案
这是您应该利用OOP,特别是多态性的优势。
interface Fooable
{
public function ihatefooexamples();
class Foo implements Fooable
{
public function ihatefooexamples()
{
returnboo-foo!;
class FooBar implements Fooable
{
public function ihatefooexamples()
{
returnreally boo-富;
}
}
$ foo = new Foo();
if(10 == $ _GET ['foolevel']){
$ foo = new FooBar();
}
echo $ foo-> ihatefooexamples();
Can you declare a function like this...
function ihatefooexamples(){
return "boo-foo!";
};
And then redeclare it somewhat like this...
if ($_GET['foolevel'] == 10){
function ihatefooexamples(){
return "really boo-foo";
};
};
Is it possible to overwrite a function that way?
Any way?
Edit
There is a function available called override_function that actually fits the bill. However, given that this function is part of The Advanced PHP Debugger extension, it's hard to make an argument that override_function()
is intended for production use. Therefore, I would say "No", it is not possible to overwrite a function with the intent that the original questioner had in mind.
Original Answer
This is where you should take advantage of OOP, specifically polymorphism.
interface Fooable
{
public function ihatefooexamples();
}
class Foo implements Fooable
{
public function ihatefooexamples()
{
return "boo-foo!";
}
}
class FooBar implements Fooable
{
public function ihatefooexamples()
{
return "really boo-foo";
}
}
$foo = new Foo();
if (10 == $_GET['foolevel']) {
$foo = new FooBar();
}
echo $foo->ihatefooexamples();
这篇关于是否有可能在PHP中覆盖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!