我有一个类:
class demo {
function newDemo(){
$v=$this->checkDemo;
$v('hello'); // not working this reference, or how to do this?
}
function checkDemo($a){
...
return $a;
}
}
那么,我如何在类内引用checkDemo函数方法?
要从对象方法中创建一个可调用对象,您需要一个数组。索引0是实例,索引1是方法的名称:
$v = Array($this,"checkDemo");
$v("hello");
编辑:请注意,此功能仅在PHP 5.4
你可以这样赋值:
$v = 'checkDemo';
$this->$v('hello');
查看文档以获取更多示例。
虽然我不完全确定为什么你会这样做,但就是这样。
PHP手册
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
如果你只是:
class demo {
function newDemo(){
echo $this->checkDemo('hello');
}
function checkDemo($a){
return $a;
}
}
$demo = new demo;
$demo->newDemo(); // directly outputs "hello", either to the browser or to the CLI
当你可以直接调用$this->checkDemo($data)
然而…你可以这样做
$v=function($text){ return $this->checkDemo($text); };
echo $v('hello');
直接调用call_user_func
函数并传递由对象引用和方法名组成的数组作为第一个参数:
class demo {
function newDemo(){
return call_user_func( array( $this, 'checkDemo' ), 'hello' );
}
function checkDemo( $a ){
...
return $a;
}
}
一种方法:
<?php
class HelloWorld {
public function sayHelloTo($name) {
return 'Hello ' . $name;
}
public function test () {
$reflectionMethod = new ReflectionMethod(__CLASS__, 'sayHelloTo');
echo $reflectionMethod->invoke($this, 'Mike');
}
}
$hello = new HelloWorld();
$hello->test();
http://www.php.net/manual/en/reflectionmethod.invoke.php 调用函数时必须添加参数:
$v = $this->checkDemo('hello');