2016-03-08 86 views
4

我有一些問題。 我想從另一個類中調用static類的方法。 動態創建類名稱和方法。

這不是真的很難做到像:

$class = 'className'; 
$method = 'method'; 

$data = $class::$method(); 

,但我想這樣做這樣

class abc { 
    static public function action() { 
     //some code 
    } 
} 

class xyz { 
    protected $method = 'action'; 
    protected $class = 'abc'; 

    public function test(){ 
     $data = $this->class::$this->method(); 
    } 
} 

如果我不分配$this->class它不工作變量$class變量,以及$this->method變量爲$method變量。 什麼問題?

+4

'$ this'總是在當前目標點 - 該方法正在執行的那個。你不能使用'$ this'並魔法般地將它變成其他對象的「this」。即使你可以做'$ this - > $ class-> action()','$ class'只是一個字符串。它不是對象,也不指向對象的實例,因此即使該對象的名稱是字符串,也不能用於在對象中執行方法。你可以使用它的唯一方法就是調用它所代表的類的一個** STATIC **方法。 –

回答

1

對象語法$this->class,$this->method在與靜態調用中的::組合時使解析器不明確。我已經嘗試了各種可變函數/字符串插值的組合,例如{$this->class}::{$this->method}()等等,但都沒有成功。因此,分配給一個局部變量是唯一的辦法,或致電這樣的:

$data = call_user_func(array($this->class, $this->method)); 

$data = call_user_func([$this->class, $this->method]); 

$data = call_user_func("{$this->class}::{$this->method}"); 

如果你需要傳遞的參數使用call_user_func_array()

1

在PHP 7.0,你可以使用這樣的代碼:

<?php 
class abc { 
static public function action() { 
    return "Hey"; 
} 
} 

class xyz { 
protected $method = 'action'; 
protected $class = 'abc'; 

public function test(){ 
    $data = $this->class::{$this->method}(); 

    echo $data; 
} 
} 

$xyz = new xyz(); 
$xyz->test(); 

對於PHP 5.6,並降低你可以使用call_user_func功能:

<?php 
class abc { 
static public function action() { 
    return "Hey"; 
} 
} 

class xyz { 
protected $method = 'action'; 
protected $class = 'abc'; 

public function test(){ 
    $data = call_user_func([ 
     $this->class, 
     $this->method 
    ]); 
    echo $data; 
} 
} 

$xyz = new xyz(); 
$xyz->test();