在新实例中重新定义类属性(在getter函数调用之前)失败

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

我在学习PHP和尝试写一份食谱小册子的class时遇到了麻烦。 pamplet中的每个食谱都有一个由标题和作者组成的标题。

在每个实例中,我尝试给出不同的标题和作者属性值,但失败了,我不知道我的错误在哪里。

class Recipe {
    private $title = 'Yet another good recipe'; # Default recipe title.
    private $author = 'John Kelly'; # Default author.

    private function setHeader($title, $author) {
        $this->title = ucwords($title);
        $this->author = 'given to us by' . ucwords($author);
    }

    private function getHeader() {
        echo $this->title;
        echo $this->author;
    }
}

$recipe1 = new Recipe();
    $recipe1->title = 'Korean Kimchi Pickles';
    $recipe1->author = 'Kim Jong Quei';
    $recipe1->getHeader();

$recipe2 = new Recipe();
    $recipe2->title = 'Tunisian Salad Sandwich';
    $recipe2->author = 'Habib Ismail';
    $recipe2->getHeader();

未捕获的错误:无法访问第19行的私有财产....

我想问为什么我得到这个错误,如果我确保所有类方面(属性/方法)是该类的私有,或者至少,因此在我看来,作为一个新生......

更新:

我认为数据(方法)对于其他类的实例是私有的,而不是那个类的实例,但我错了,即使对于那个特定类的实例它们也是私有的。这就是为什么我错过了错误的意图和阅读答案,我知道我可以通过公共方法访问私有财产(虽然我也可以公开所有数据)。

php class methods properties
2个回答
0
投票

您将getHeader和setHeader定义为私有,并且您打算在类外部使用它。这肯定会失败,你需要公开它。此外,您打算写一些私有属性的值。你不应该这样做,而是使用setHeader:

class Recipe {
    private $title = 'Yet another good recipe'; # Default recipe title.
    private $author = 'John Kelly'; # Default author.

    public function setHeader($title, $author) {
        $this->title = ucwords($title);
        $this->author = 'given to us by' . ucwords($author);
    }

    public function getHeader() {
        echo $this->title;
        echo $this->author;
    }
}

$recipe1 = new Recipe();
    $recipe1->setHeader('Korean Kimchi Pickles', 'Kim Jong Quei');
    $recipe1->getHeader();

$recipe2 = new Recipe();
    $recipe2->setHeader('Tunisian Salad Sandwich', 'Habib Ismail');
    $recipe2->getHeader();

请注意,这是使您的成员private成为一种好方法,但是您需要通过public方法使用它们。此外,我不确定echo价值观是一个好主意。返回值并在class函数之外回显它们可能更有意义。


0
投票

您已将类中的所有内容(方法和属性)声明为private,但您无法访问类定义之外的私有类属性,这就是您收到错误(Visibility in PHP)的原因。

为了能够访问类的某些内容,您应该在类中公开公共方法。那个/那些方法可以访问/修改私有属性。

只有当您希望将其访问权限保持为类的私有时才应声明方法或属性为私有,以便您可以控制属性或类数据的修改。

© www.soinside.com 2019 - 2024. All rights reserved.