二传手的getter功能在PHP类

问题描述:

我是新来的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功能。

为什么没有任何印刷?

<?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; 

?> 

你从来没有设置对象的标题。你已经使用了得到功能,只需打印出没有在这种情况下。

调整

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

在你的情况下,您不需要为get函数的参数。

在您的两个食谱示例中,您从不设置标题,因为您正在调用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" 

你混在一起的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'