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;


图片转代码服务由CSDN问答提供 功能建议


例如,在 WordPress 中,您有一个函数 get_option( ); 从选项数据库表中按名称获取值。 是否允许这样做:

  class ExampleClass {
公共静态函数ExampleMethod($ optionName){
 if(get_option($ optionName)){  
返回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();

    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:


    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题