从静态方法调用非静态方法

zar*_*pio 2 php oop function

我认为这是非常基本的功能,请帮忙.如何在php中将非静态方法调用为static-method.

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

    public static function countriesDropdown() {
        $this->getCountries();
    }
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*ran 5

首选方式..

最好将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
Run Code Online (Sandbox Code Playgroud)

添加self关键字会显示PHP严格标准注意事项为了避免这种情况,您可以创建同一个类的对象实例并调用与之关联的方法.

从静态方法调用非静态方法

<?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
Run Code Online (Sandbox Code Playgroud)

  • 是的你是对的,但有一个警告严格的标准:非静态方法Country :: getCountries()不应该静态调用 (2认同)