我认为这是非常基本的功能,请大家帮忙。 如何在PHP中将静态方法调用非静态方法。从静态方法调用非静态方法
class Country {
public function getCountries() {
return 'countries';
}
public static function countriesDropdown() {
$this->getCountries();
}
}
我认为这是非常基本的功能,请大家帮忙。 如何在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严格标准的通知要避免你可以创建非常相同的类的对象实例,并调用与它相关的方法。
<?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
是的,你是对的,但有一个警告严格的标准:非静态方法国家:: getCountries()不应该静态调用 – zarpio
对不起,我不在了..为了避免你可以创建一个实例内的静态函数同班同学。 –
@zarpio,我只是想知道为什么不让getCountries()方法变成静态的呢?所以你没有经历所有这些障碍;) –
你甚至可以使用Class Name
public static function countriesDropdown() {
echo Country::getCountries();
}
是的,你是对的,但有警告严格的标准:非静态方法国家:: getCountries()不应该静态调用 – zarpio
你不能简单的做了,你需要创建类&有一个实例拨打非静电方式,
class Country {
public function getCountries() {
return 'countries';
}
public static function countriesDropdown() {
$country = new Country();
return $country->getCountries();
}
}
DEMO。
但是,为什么'getCountries'也不是一个静态方法,因为它根本不使用'$ this'? – SirDarius