2017-04-25 126 views
0

我基本上有2个有关查询:有没有办法从PHP函数中获取打印值而不返回?

考虑一类以下PHP函数说xyz.php

function sendResponse(){ 
    $car="Lambo"; 
    echo $car; 
} 
function sendResponseTwo(){ 
    $car="Lambo"; 
    echo $car; 
    return $car; 
} 
function getResponse(){ 
    //case 1: 
    $carName=$this->sendResponse(); 
    //ABOVE WON'T WORK AS THE FUNCTION RETURNS NOTHING. 

    //case 2: 
    $carName=$this->sendResponseTwo(); 
    //THIS WILL PRINT THE NAME OF CAR 
} 
  1. 在案例1中,有没有办法通过获取回波值在另一个函数中调用函数,但不使用返回语句

  2. 在case2中,有没有什么办法来停止echo语句打印的值(我只想返回值)?

+1

输出缓冲。 – CBroe

+0

那是什么。任何链接? –

+1

试试这些http://php.net/manual/en/function.ob-start.php http://php.net/manual/en/function.ob-get-contents.php –

回答

1

回答你的问题都在output buffer(ob),希望这会帮助你理解。这里我们使用的三个函数ob_start()会启动输出缓冲区,而ob_end_clean()会清空缓冲区的输出,而​​会给你输出字符串,直到现在都回显。 This将帮助您更好地了解​​

Try this code snippet here

<?php 

class x 
{ 
    function sendResponse() 
    { 
     $car = "Lambo1"; 
     echo $car; 
    } 

    function sendResponseTwo() 
    { 
     $car = "Lambo2"; 
     echo $car; 
     return $car; 
    } 

    function getResponse() 
    { 
     //case 1: 
     $carName = $this->sendResponse(); 
     //ABOVE WON'T WORK AS THE FUNCTION RETURNS NOTHING. 
     //case 2: 
     $carName = $this->sendResponseTwo(); 
     //THIS WILL PRINT THE NAME OF CAR 
    } 

} 
ob_start();//this will start output buffer 
$obj= new x(); 
$obj->getResponse(); 
$string=ob_get_contents();//this will gather complete content of ob and store that in $string 
ob_end_clean();//this will clean the output buffer 
echo $string; 
?> 
1

您需要使用输出缓冲:

ob_start(); 
$foo->sendResponse(); 
$response = ob_get_clean(); 

这就是为什么它不是摆在首位一个实用的设计。如果你做的功能总是返回值是微不足道的两件事要做自己的喜好:

$response = $foo->sendResponse(); 
echo $foo->sendResponse(); 
<?=$foo->sendResponse()?> 

(最后一个选项是用于说明目的共享,不打算开一个火焰关于短打开标签的战争。)

相关问题