2017-04-25 49 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()?> 

(最後一個選項是用於說明目的共享,不打算開一個火焰關於短打開標籤的戰爭。)

相關問題