我认为这是非常基本的功能,请帮忙.如何在php中将非静态方法调用为static-method.
class Country {
public function getCountries() {
return 'countries';
}
public static function countriesDropdown() {
$this->getCountries();
}
}
Run Code Online (Sandbox Code Playgroud)
最好将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)
| 归档时间: |
|
| 查看次数: |
149 次 |
| 最近记录: |