说我有一个来自对象的函数:
class Cat {
protected $sound = 'MeOwWw~';
public function make_a_big_and_nice_sound () { echo $this->sound; }
}
$C = new Cat;
$C->make_a_big_and_nice_sound ();
现在,函数的名称可能很长,内容取决于对象本身的某些属性,因此不能在Object之外重写。
但是,假设我只生了一只猫,我想在我的代码中make a a。。。。。。。。。。。。。。我想做的是以下几点:
main.php
function please_meow = $C->make_a_big_and_nice_sound;
please_meow ();
答案 0 :(得分:2)
如果您的方法名称很长,那么您的方法很有可能做得太多。方法应该只做一件事。
所以你应该真正修改你的代码。
考虑到你没有提供你的实际代码(这有助于指出代码中的实际缺陷),如果你真的坚持这样做(你真的不应该),你可以使用{ {3}}为此:
$please_meow = function() use ($C) {
return $C->make_a_big_and_nice_sound();
};
$please_meow();
但是,如果你需要这个,你做错了。
答案 1 :(得分:1)
如果您使用的是PHP 5.3或更高版本,请尝试以下操作:
$please_meow = function() use($C) { $C->make_a_big_and_nice_sound(); };
$please_meow();
答案 2 :(得分:-1)
现在,函数的名称可能很长,内容依赖于对象本身的某些属性,因此无法在对象之外重写。
但是,让我说我只有一只猫可以生下来,我想做 它在我的代码中喵喵了很多时间
你可以做这样的事情
class Cat
{
protected static $instance;
function __construct()
{
self::$instance = $this;
}
public static function please_meow()
{
self::$instance->make_a_big_and_nice_sound();
}
protected $sound = 'MeOwWw~';
public function make_a_big_and_nice_sound () { echo $this->sound; }
}
new Cat();
Cat::please_meow();
Cat::please_meow();
// some other codes
Cat::please_meow();