簡體   English   中英

不使用$ this-> function_name()調用類函數 - PHP -

[英]Calling a Class function without using $this->function_name() — PHP --

所以我有這門課:

class A{
      public function do_a(){ return 'a_done';};

      public function do_b(){ return 'b_done';};
}

所以我需要php文件並創建該類的實例:

require_once("A_class.php");
$System = new A();
require_once("user_calls.php"); //here I import the user file with the function calls.

user_calls.php內容:

echo 'this was the result of '.$System->do_a();
echo 'this was the result of '.$System->do_b();

所以,這確實有效,但我不希望用戶必須使用$System->do_a(); ,但只有do_a();

有解決方案嗎

編輯:我還想限制用戶可以在user_calls.php文件中調用的函數,基本的本機php函數和A類中的函數。

免責聲明:雖然此代碼有效,並且按照您的要求執行,但這並不意味着我提倡像這樣編碼。 對於其他開發人員來說很難跟上(甚至可能在將來也是如此......),它也會使用eval() ,這幾乎總是一件壞事(tm)。 那就是說,你走了:

<?php
class A {
    public function do_a() {
        return __METHOD__;
    }

    public function do_b() {
        return __METHOD__;
    }
}

$aRef = new ReflectionClass('A');
$aPublicMethods = $aRef->getMethods(ReflectionMethod::IS_PUBLIC);

foreach ($aPublicMethods as $method) {
    $php = <<<PHP
function {$method->name}() {
    global \$System;
    return \$System->{$method->name}();
}
PHP;

    eval($php);
}

$System = new A();

echo 'this was the result of ' . do_a();
echo 'this was the result of ' . do_b();

還請注意,如果您的方法使用參數,事情會變得更加毛茸茸。 此外,如果您將任何方法命名為全局命名空間中的函數(例如substr() ),則會嘗試重新定義它們,並且您可能會收到致命錯誤。

類的方法是實例方法(它們作用於由$ this定義的類的特定實例)或者它們是類方法(它們不依賴於類的任何一個特定實例,而是提供屬於該類的服務。課程的職權范圍。

實例方法定義如下:

public function foo()
{
}

而使用STATIC關鍵字定義類方法。

static public function bar()
{
}

在實例方法中,您可以使用$ this來訪問調用該方法的實例的狀態。 這在類方法中不可用,因為它不依賴於任何一個實例。 它可以使用self關鍵字訪問類的其他成員(假設它們不與實例綁定)。

實例方法調用如下:

$a = new ObjType ()
$output = $a -> foo ();

類方法調用如下:

$output = ObjType::bar ();

無論您使用哪種方法,您都必須提供實例(例如方法)或類(用於類方法)來調用方法。 只調用foo()bar()將不起作用。

你必須使用一個閉包。 請注意,它直接從類定義調用,而不是對象:

class test {
    function method() {
        echo 'method was called';
    }
}

$method = function(){call_user_func('test::method');};
$method();
$method();
$method();

//output:
//method was calledmethod was calledmethod was called

要從對象而不是類中調用方法,您必須將對象傳遞給閉包:

class test {
    var $count = 0;
    function method() {
        $this->count++;
        echo $this->count . "|<br />";
    }
}

$obj = new test;
$obj2 = new test;
$method = function($object){call_user_func(array($object, 'method'));};
$method($obj);
$method($obj);
$method($obj);
$method($obj2);
//output:
//1|
//2|
//3|
//1|

但這不是更漂亮或更簡單,是嗎?

如果您不想弄亂頁面,只需將對象命名為簡短:

$pco = new page_controller_object_with_a_long_name_that_is_annoying;
$pco->do_a();
$pco->do_b();
//etc.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM