2017-12-18 309 views
-3

我是新來的PHP寫了這樣的代碼,包括類和兩個實例失敗。該類包含一個setter和getter方法來訪問私有title屬性,每個實例顯示它,當所有的標題文字,被ucwords()功能大寫。在這種情況下,它還包含一個「作者」屬性。二傳手的getter功能在PHP類

當我執行代碼時,我什麼都沒有(既不是title也不是author),也沒有任何錯誤,所以我不知道我做錯了什麼(我做它作爲個人練習的一部分在teamtreehouse.com學習時)。

class Recipe { 
    private $title; 
    public $author = "Me myself"; 

    public function setTitle($title) { 
     echo $this->title = ucwords($title); 
    } 
    public function getTitle($title) { 
     echo $this->title; 
    } 
} 

$recipe1 = new Recipe(); 
    $recipe1->getTitle("chinese tofu noodles"); 
    $recipe1->author; 

$recipe2 = new Recipe(); 
    $recipe2->getTitle("japanese foto maki"); 
    $recipe2->author = "A.B"; 

注:AFAIU從teamtreehous.com視頻,如果我們想訪問私有財產需要一個setter的getter功能。

爲什麼沒有任何印刷?

回答

3
<?php 

class Recipe { 

    private $title; 
    public $author = "Me myself"; 

    /* Private function for set title */ 
    private function setTitle($title) { 
     echo $this->title = ucwords($title); 
    } 

    /* public function for get title */ 
    public function getTitle($title) { 
     $this->setTitle($title); 
    } 
} 

$recipe = new Recipe(); // creating object 
    $recipe->getTitle("chinese tofu noodles"); // calling function 
    echo "<br>"; 
    echo $recipe->author; 

?> 
0

你從來沒有設置對象的標題。你已經使用了得到功能,只需打印出沒有在這種情況下。

調整

<?php 
$recipe1 = new Recipe(); 
//set the title 
$recipe1->setTitle("chinese tofu noodles"); 
//get the title 
$recipe1->getTitle(); 

在你的情況下,您不需要爲get函數的參數。

0

在您的兩個食譜示例中,您從不設置標題,因爲您正在調用getTitle。 此外,的getTitle不會因爲你沒有在你的函數中使用它需要的參數。

對於作者,你根本不打印任何東西。

此代碼應工作:

class Recipe { 
    private $title; 
    public $author = "Me myself"; 
    public $ingredients = array(); 
    public $instructions = array(); 
    public $tag = array(); 

    public function setTitle($title) { 
     echo $this->title = ucwords($title); 
     echo $this->author; 
    } 
    public function getTitle() { // Removing parameter as it's unused 
     echo $this->title; 
    } 
} 

$recipe1 = new Recipe(); 
    $recipe1->setTitle("chinese tofu noodles"); // set the title 
    $recipe1->getTitle(); // print the title 
    echo $recipe1->author; // Will print "Me myself" 

$recipe2 = new Recipe(); 
    $recipe2->setTitle("japanese foto maki"); // set the title 
    $recipe2->getTitle(); // print the title 
    echo $recipe2->author = "A.B"; // Will print "A.B" 
2

你混在一起的getter,setter和echo。吸氣者不應該接受參數並返回屬性。 Setters接受參數並設置屬性。 echo輸出(文本)字符串到屏幕。

echo的文檔。

class Recipe { 
    private $title; 
    public $author = "Me myself"; 

    public function setTitle($title) { 
     $this->title = ucwords($title); 
    } 

    public function getTitle() { 
     return $this->title; 
    } 
} 
$noodles = new Recipe(); 
$noodles->setTitle("chinese tofu noodles"); 
echo ($noodles->getTitle); 
//outputs 'chinese tofu noodles'