4

私はクラスを持っています:

class demo {

      function newDemo(){
          $v=$this->checkDemo;
          $v('hello'); // not working this reference, or how to do this?
      }

      function checkDemo($a){
          ...
          return $a;
      }
           }

では、クラス内で checkDemo 関数メソッドを参照するにはどうすればよいですか?

4

8 に答える 8

8

オブジェクト メソッドから callable を作成するには、配列が必要です。インデックス 0 はインスタンスで、インデックス 1 はメソッドの名前です。

$v = Array($this,"checkDemo");
$v("hello");

EDIT:この機能はPHP 5.4以降でのみ利用可能であることに注意してください

于 2013-03-06T14:54:35.823 に答える
5

You assign it like so:

$v = 'checkDemo';
$this->$v('hello');

Check out the documentation for more examples.

Although I'm not entirely sure why you'd do it, that's how.

于 2013-03-06T14:54:57.057 に答える
1

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()

?>
于 2013-03-06T14:56:37.750 に答える
0

関数を呼び出しcall_user_funcて配列を渡すだけで、最初のパラメーターとしてオブジェクト参照とメソッド名で構成されます。

class demo {

      function newDemo(){
          return call_user_func( array( $this, 'checkDemo' ), 'hello' );
      }

      function checkDemo( $a ){
          ...
          return $a;
      }
}
于 2013-03-06T15:00:43.257 に答える
0

$this->checkDemo($data) を直接呼び出すことができる場合は役に立ちません。

ただし....このようにすることができます

$v=function($text){ return $this->checkDemo($text); };
echo $v('hello');
于 2013-03-06T14:56:59.057 に答える
0

次のようにすれば、はるかに簡単でシンプルになります。

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
于 2013-03-06T14:53:26.793 に答える
0

これを行う1つの方法:

<?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

于 2013-03-06T15:03:20.957 に答える
-2

関数を呼び出すときは、引数を追加する必要があります。

$v = $this->checkDemo('hello');
于 2013-03-06T14:54:05.607 に答える