簡體   English   中英

PHP:在同一類中調用內部(函數)方法

[英]PHP: Call an internal (Function) method within the same class

我不想在每個方法上使用多行相同代碼,而是要設置(引導/初始化)方法來定義通用值等等。 然后,在需要時調用該方法。

最初,我有這樣的事情:

<?php
class boot {
    private static $root = $_SERVER['DOCUMENT_ROOT'] . '/';


    public static function load() {
        return self::$root;
    }
}

$test = boot::load();
echo $test;
?>

但是我會收到類似以下內容的錯誤消息:解析錯誤:語法錯誤,意外的T_VARIABLE輸入...

因此,我將其更改為:

<?php /* Class Bootstrap (Boot for short) */
class boot {
    private static $base = null;
    private static $root = null;


    private static function boot(){
        self::$base = $_SERVER['DOCUMENT_ROOT'] . '/';
    }


    public static function load() {
        self::boot();
        return self::$base;
    }
}

$test = boot::load();
echo $test;
?>

然后我得到了: 致命錯誤:構造函數boot :: boot()在...中不能是靜態的。

所以我訴諸:

<?php
class boot {
    private static $base = null;
    private static $root = null;


    private function boot(){
        $this->base = $_SERVER['DOCUMENT_ROOT'] . '/';
    }


    public static function load() {
        $this->boot();
        return self::$base;
    }
}

$test = boot::load();
echo $test;
?>

但是我仍然遇到錯誤, 致命錯誤:在不在對象上下文中時使用$ this ...我嘗試了不同的方法,但是我沒有主意。

您不能在靜態上下文中使用$ this。

何時在$ this上使用self?

總結以上答案,您必須使用$ this訪問屬於當前Object的成員(非靜態),但使用self ::訪問類的靜態成員。

您可以將所有函數設為靜態,並使用self ::而不是$ this->。

嘗試以下

class boot {
    private static $base = null;
    private static $root = null;

    public static function load() {
        self::$base = $_SERVER['DOCUMENT_ROOT'] . '/';
        return self::$base;
    }
}

$test = boot::load();
echo $test;

暫無
暫無

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

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