簡體   English   中英

從靜態方法調用非靜態方法

[英]Calling a non-static method from a static method

我認為這是非常基本的功能,請幫助。 如何在php中將非靜態方法調用為靜態方法。

class Country {
    public function getCountries() {
        return 'countries';
    }

    public static function countriesDropdown() {
        $this->getCountries();
    }
}

首選方式..

最好將getCountries()方法改為靜態

<?php

class Country {
    public static function getCountries() {
        return 'countries';
    }

    public static function countriesDropdown() {
        return self::getCountries();
    }
}
$c = new Country();
echo $c::countriesDropdown(); //"prints" countries

添加self關鍵字會顯示PHP Strict Standards Notice避免您可以創建相同類的對象實例並調用與其關聯的方法。

從靜態方法調用非靜態方法

<?php

class Country {
    public function getCountries() {
        return 'countries';
    }

    public static function countriesDropdown() {
        $c = new Country();
        return $c->getCountries();
    }
}

$c = new Country();
echo $c::countriesDropdown(); //"prints" countries

你甚至使用Class Name

public static function countriesDropdown() {
    echo Country::getCountries();
}

您不能直接這樣做,因為您需要創建類的實例並且必須調用非靜態方法,

class Country {
    public function getCountries() {
        return 'countries';
    }

    public static function countriesDropdown() {
        $country = new Country();
        return $country->getCountries();
    }
}

演示

暫無
暫無

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

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