繁体   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