是否可以覆盖PHP中的函数 [英] Is it possible to overwrite a function in PHP

查看:43
本文介绍了是否可以覆盖PHP中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能声明这样的函数吗...

function ihatefooexamples(){返回 "boo-foo!";};

然后重新声明有点像这样......

if ($_GET['foolevel'] == 10){函数 ihatefooexamples(){返回真的很糟糕";};};

是否有可能以这种方式覆盖一个函数?

有什么办法吗?

解决方案

编辑

<块引用>

为了解决这个答案没有直接解决原始问题.如果您是通过 Google 搜索来到这里的,请从这里开始

有一个名为 override_function 的函数,它实际上符合要求.但是,鉴于此功能是 The Advanced PHP Debugger 扩展的一部分,因此很难论证 override_function() 用于生产用途.因此,我会说不",不可能以原始提问者的意图覆盖一个函数.

原答案

这是您应该利用 OOP 的地方,特别是多态性.

接口 Fooable{公共函数 ihatefooexamples();}类 Foo 实现 Fooable{公共函数 ihatefooexamples(){返回 "boo-foo!";}}类 FooBar 实现 Fooable{公共函数 ihatefooexamples(){返回真的很糟糕";}}$foo = new Foo();if (10 == $_GET['foolevel']) {$foo = 新的 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

To address comments that this answer doesn't directly address the original question. If you got here from a Google Search, start here

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中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆