突發(fā)奇想,php能不能實現(xiàn)類似java 那種把interface 類當作方法的參數(shù)呢?
java 代碼如下:
interface TestInterface{
void test(String param);
}
public class Test(){
private static TestInterface testInterface;
public static void setTestInterface(TestInterface testInterface){
this.testInterface=testInterface;
}
public static void action(){
this.testInterface.test("param") ;
}
public static void main(String[] args){
Test test =new Test();
test.setTestInterface(new TestInterface(){
@Override
public void test(String p){
System.out.print(p);
}
})
}
}
經(jīng)過調查,在國內的帖子上沒有找到類似的實現(xiàn)。只好求助于google 了。我在 stackoverflow 上發(fā)布了一個帖子,然而第二天被告知和其他問題重復了。我看了那個問題,和我想要的差不多。
stackoverflow上的回答。
經(jīng)過修改,PHP 實現(xiàn)的代碼如下:
<?php
// 定義interface
interface TestInterface{
public function test($p);
}
class Test{
// 定義類內全局變量
public TestInterface $testInterface;
// interface 變量的set 方法(也可以說是interface具體實現(xiàn))
public function setTestInterface(TestInterface $interface){
$this->testInterface = $interface;
}
// 使用interface 的具體操作
public function action($p){
$this->testInterface->test($p);
}
// 測試方法
public function main($param){
$this->setTestInterface(new class implements TestInterface{
public function test($p){
echo $p;// 打印傳遞進來的參數(shù)
}
});
$this->action($param);
}
}
// 測試
$test = new Test();
$test->main("test1");
$test->main("test2");
輸入結果是文章來源:http://www.zghlxwxcb.cn/news/detail-577322.html
test1
test2
以上就是在php 中 interface 作為function函數(shù)的參數(shù),怎么在方法中實現(xiàn)interface。文章來源地址http://www.zghlxwxcb.cn/news/detail-577322.html
到了這里,關于PHP 在function中直接實例化interface,不用再class 后 implement的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!