1

私は使用方法を知っています:

call_user_func_array(array($className, $methodName), array($_POST)) ;

クラスで関数を呼び出してパラメーターを送信するには。

しかし、クラスだけを呼び出して、__コンストラクターに入るパラメーターを渡すにはどうすればよいでしょうか?

手動で行うには、次のようにします。

$myTable = new Supertable(array('columnA', 'columnB'), 5, 'Some string') ;

どちらがうまくいくでしょう。call_user_func_array と同様の機能を実現するには、どのような関数が必要ですか?

ここに、私がやっていることの完全なコンテキストがあります:

function __autoload($classname) {
    @include $classname.'.php' ;
}

$className = 'supertable' ;
$methodName = 'main' ;

if(class_exists($className, true)) {
    if(method_exists($className, $methodName)) {
        $reflection = new ReflectionMethod($className, $methodName) ;

        if($reflection->isPublic()){
            call_user_func_array(array($className, $methodName), array($_POST)) ;
        } elseif($reflection->isPrivate()) {
            echo '<span class="state">Private</span> method <span class="methodname">'.$methodName.'</span> can not be accessed directly.' ;
        } elseif($reflection->isProtected()) {
        echo '<span class="state">Protected</span> method <span class="methodname">'.$methodName.'</span> can not be accessed directly.' ;
        }

    } else {
        echo 'The method <span class="methodname">'.$methodName.'</span> does not exist.' ;
    }
} else {
    echo 'The class <span class="classname">'.$className.'</span> does not exist.' ;
}
4

2 に答える 2

0

それがまさにあなたが必要とするものである場合、2つの理由で要点がわかりません。

  1. 次の方法で簡単に呼び出すことができます。

    new $className($_POST);
    
  2. $_POSTはスーパーグローバルであり (これはご存じだと思います)、アクセス可能にするためにパラメーターとして渡す必要はありません。

于 2012-11-14T20:02:23.263 に答える
0

ここで私自身の質問への答えを見つけました:

PHP で call_user_func_array を使用してコンストラクターを呼び出す方法

参考までに、スクリプトを次のように変更しました。

function __autoload($classname)
{
    @include $classname.'.php' ;
}

$className = 'supertable' ;
$methodName = '' ;

if(class_exists($className, true))
{
if(method_exists($className, $methodName))
{
    $reflection = new ReflectionMethod($className, $methodName) ;

    if($reflection->isPublic())
    {
        call_user_func_array(array($className, $methodName), array($_POST)) ;
    }
    elseif($reflection->isPrivate())
    {
        echo '<span class="state">Private</span> method <span class="methodname">'.$methodName.'</span> can not be accessed directly.' ;
    }
    elseif($reflection->isProtected())
    {
        echo '<span class="state">Protected</span> method <span class="methodname">'.$methodName.'</span> can not be accessed directly.' ;
    }

} else {
    $reflect  = new ReflectionClass($className);
    $reflect->newInstanceArgs(array($_POST));
}
} else {
echo 'The class <span class="classname">'.$className.'</span> does not exist.' ;
}

したがって、クラスが存在するがメソッドが指定されていない場合、コンストラクターが呼び出されます。

于 2012-11-14T19:53:36.003 に答える