简体   繁体   English

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

[英]Calling a non-static method from a static method

I think it is very basic functionality, please help.我认为这是非常基本的功能,请帮助。 How can I call non-static method into static-method in php.如何在php中将非静态方法调用为静态方法。

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

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

Preferred way..首选方式..

It is better to make the getCountries() method static instead.最好将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

Adding a self keyword displays the PHP Strict Standards Notice To avoid that you can create an object instance of the very same class and call the method associated with it.添加self关键字会显示PHP Strict Standards Notice避免您可以创建相同类的对象实例并调用与其关联的方法。

Calling a non-static method from a static method从静态方法调用非静态方法

<?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

You even use Class Name你甚至使用Class Name

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

You cannot straight forward do that for that you need create a instance of the class & have to call the non-static method,您不能直接这样做,因为您需要创建类的实例并且必须调用非静态方法,

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

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

DEMO .演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM