Can I override the PHP built-in function echo()?

后端 未结 6 1184
無奈伤痛
無奈伤痛 2020-12-11 15:02

I recently looked at my source code and it was a real mess.

my php source:

echo \'

Rar

\'; echo \'Rar\'; e

6条回答
  •  春和景丽
    2020-12-11 16:01

    You can indirectly overload echo() by using the __toString() magic method like so:

    content= $c;
        }
    
        public function __toString() {
            return $this->content . '\r\n';
        }
    }
    
    $text= new CleanOutput('Hello world!');
    echo $text;
    ?>
    

    The above would output "Hello world!" with a newline and carriage return appended at the end. There's ways to further encapsulate this, but they are outside the scope of my answer.

    Edit:
    As was noted, the above solution is slow/clumsy. Here's a more elegant solution using output buffering:

    
    

    This is faster and cleaner (although it technically doesn't 'override' echo).

提交回复
热议问题