2014-03-24 175 views
2

我认为这是非常基本的功能,请大家帮忙。 如何在PHP中将静态方法调用非静态方法。从静态方法调用非静态方法

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

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

但是,为什么'getCountries'也不是一个静态方法,因为它根本不使用'$ this'? – SirDarius

回答

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 

添加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 
+2

是的,你是对的,但有一个警告严格的标准:非静态方法国家:: getCountries()不应该静态调用 – zarpio

+0

对不起,我不在了..为了避免你可以创建一个实例内的静态函数同班同学。 –

+0

@zarpio,我只是想知道为什么不让getCountries()方法变成静态的呢?所以你没有经历所有这些障碍;) –

1

你甚至可以使用Class Name

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

是的,你是对的,但有警告严格的标准:非静态方法国家:: getCountries()不应该静态调用 – zarpio

1

你不能简单的做了,你需要创建类&有一个实例拨打非静电方式,

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

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

DEMO

相关问题