duanran6441 2015-08-23 15:51
浏览 47
已采纳

是否允许在OOP PHP方法中使用过程函数?

I am learning Object oriented PHP and I am wondering if it is allowed to use procedural functions inside methods.

For example in WordPress you have a function get_option(); to get a value by name from the options database table. Is it allowed to do something like this:

class ExampleClass {

   public static function ExampleMethod( $optionName ) {
      if( get_option( $optionName ) ) {
         return get_option( $optionName ) + 20;
      }     
   }

}
  • 写回答

2条回答 默认 最新

  • doubingjiu3199 2015-08-23 16:29
    关注

    Is it allowed to use procedural functions inside OOP PHP methods?

    Well the first question would be is it even possible. And why don't we try it out:

    class A {
    
        public static function randomStaticMethod() {
            echo "Function call:" . phpversion();
        }
    
        public function randomMethod() {
            echo "Function call:" . phpversion();
        }
    
    }
    
    $o = new A();
    $o->randomMethod();
    
    A::randomStaticMethod();
    

    And you will see it will work as expected, no errors no warnings, just:

    Function call: ...
    Function call: ...
    

    So it's definitely possible. Now to your question: Is it allowed?

    Simple question, which should answer your question:

    How would you get the length of a string, when you wouldn't be allowed to use functions like strlen() in a class?

    So yes it's also definitely allowed and used.


    Now a few other things, which might be useful to know. If you work with namespaces you have to be careful.

    As example:

    namespace I_AM_A_NAMESPACE;
    
    function strlen() {
        echo "nope";
    }
    
    echo strlen("xyz");
    echo \strlen("xyz");
    

    Your output will be:

    nope
    3
    

    So if you work with namespaces you have to know in which namespace you are and which function you want to call. So if you want to call the global function strlen() and you want to take the save route, always put a \ in front of it, to make sure you call the global strlen() function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开