【问题标题】:non static not called statically非静态不静态调用
【发布时间】:2017-02-04 08:05:36
【问题描述】:

如何动态调用该方法? 我已经调用了函数:

    public function type_bien($value)
    {
        $stype['1'] = "Maison";
        $stype['2'] = "Appartement";
        $stype['4'] = "Appartement meublé";
        $stype['7'] = "Propriété";
        return $stype[$value];
    }

<?php echo type_bien($row['type_bien']); ?>

-> Returns: Deprecated: Non-static method Utils::type_bien() should not be called statically

【问题讨论】:

  • 你正在返回一些东西,所以你应该像这样调用函数:&lt;?php $myResult = type_bien($row['type_bien']); echo $myResult; ?&gt;
  • 您能否更具体地说明为什么将其声明为公共函数而不将其包装在类中?它是函数还是类方法?
  • Emn1ty-> 这其实是一个类:
  • class Utils { public function type_bien($value) { $stype['1'] = "Maison"; $stype['2'] = "公寓"; $stype['4'] = "公寓meublé"; $stype['7'] = "专有été";返回 $stype[$value]; } }
  • 当我打电话时:

标签: php static call


【解决方案1】:

你可以创建一个 Utils 类的对象

class Utils {
 public function type_bien($value) {
    $stype['1'] = "Maison";
    $stype['2'] = "Appartement";
    $stype['4'] = "Appartement meubl&eacute;";
    $stype['7'] = "Propri&eacute;t&eacute;";
    return $stype[$value];
 }
}

$utils = new Utils();
echo $utils->type_bien($row['type_bien']);

或者您可以将方法定义为静态函数

class Utils {
 public static function type_bien($value) {
    $stype['1'] = "Maison";
    $stype['2'] = "Appartement";
    $stype['4'] = "Appartement meubl&eacute;";
    $stype['7'] = "Propri&eacute;t&eacute;";
    return $stype[$value];
 }
}

echo Utils::type_bien($row['type_bien']);

【讨论】:

  • 好的,工作正常。我现在明白了。非常感谢您的参与。我很感激。
【解决方案2】:

如果您尝试动态调用方法,请查看以下示例:

<?php

Class Demo {
    public function test () {
      echo "OK";
    }
}

$demo_1= new Demo();
$dynamic = "test";

$demo_1->{$dynamic}();

// i.e. $demo_1->test();
// prints OK

// or

Demo::{$dynamic}();
// i.e. Demo::test();
// prints OK

?>

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 2013-03-20
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多