在PHP类中,Setter-getter功能失败

问题描述 投票:-3回答:4

我是PHP的新手并编写了这段代码,其中包括一个类和两个实例。该类包含一个setter和getter方法,用于访问私有title属性,以便在所有标题词由ucwords()函数大写时显示每个实例。它还包含该上下文中的“authors”属性。

当我执行代码时,我得不到任何东西(既没有title也没有author),也没有任何错误,所以我不知道我做错了什么(我在团队中学习时将其作为个人练习的一部分.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";

注意:来自teamtreehous.com视频的AFAIU,如果我们想要访问私有财产,则需要setter-getter功能。

为什么没有印刷?

php class
4个回答
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;

?>

2
投票

你混淆了吸气剂,二传手和echo。 Getters不应该接受参数并返回属性。 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'

0
投票

你永远不会设置对象的标题。您已经使用了get函数,在这种情况下只打印出任何内容。

调整

<?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"
© www.soinside.com 2019 - 2024. All rights reserved.