致命错误: 调用未定义的方法 ShopProduct编写器::获取生产者()

我遇到了一个问题:

致命错误: 调用未定义的方法 ShopProductWriter::getProducer() 在 C:\OSPanel\域\zandstra.com\索引.php第 37 行

是什么原因造成的?

<?php


class ShopProduct {

    public $title;

    public $producerSurName;

    public $producerFirstName;

    public $price = 0;


    public function __construct (

        $title,

        $firstName,

        $surName,

        $price

    )


    {

        $this->title = $title;

        $this->producerFirstName = $firstName;

        $this->producerSurName = $surName;

        $this->price = $price;

    }


    public function getProducer () {

        return $this->producerFirstName . " " . $this->producerSurName;

    }

}

$product1 = new ShopProduct (

    "My Antonia",

    "Willa",

    "Cather",

    "5.99"

);



class ShopProductWriter {

    public function write ($shopProduct){

        $str=$shopProduct->title . ":" . $shopProduct->getProducer()

            . " (".$shopProduct->price.")\n";

        print $str;

    }

}

$product1 = new ShopProductWriter("My Antonia", "Willa", "Cather", 5.99);

$writer = new ShopProductWriter();

$writer->write($product1);


皈依舞
浏览 81回答 1
1回答

回首忆惘然

这里$product1 = new ShopProductWriter("My Antonia", "Willa", "Cather", 5.99);你重新创建了 ,直到那时是一个.由此,是一个对象。这没有方法,它只有一种方法。这是你代码中的一个拼写错误,我认为你已经多次重写了你的代码,一些旧的初始化离开了,你应该已经离开了。在这种形式下,可能做你想要的:$product1ShopProduct$product1ShopProductWritergetProducer()write()<?phpclass ShopProduct {&nbsp; &nbsp; public $title;&nbsp; &nbsp; public $producerSurName;&nbsp; &nbsp; public $producerFirstName;&nbsp; &nbsp; public $price = 0;&nbsp; &nbsp; public function __construct (&nbsp; &nbsp; &nbsp; &nbsp; $title,&nbsp; &nbsp; &nbsp; &nbsp; $firstName,&nbsp; &nbsp; &nbsp; &nbsp; $surName,&nbsp; &nbsp; &nbsp; &nbsp; $price&nbsp; &nbsp; )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->title = $title;&nbsp; &nbsp; &nbsp; &nbsp; $this->producerFirstName = $firstName;&nbsp; &nbsp; &nbsp; &nbsp; $this->producerSurName = $surName;&nbsp; &nbsp; &nbsp; &nbsp; $this->price = $price;&nbsp; &nbsp; }&nbsp; &nbsp; public function getProducer () {&nbsp; &nbsp; &nbsp; &nbsp; return $this->producerFirstName . " " . $this->producerSurName;&nbsp; &nbsp; }}class ShopProductWriter {&nbsp; &nbsp; public function write ($shopProduct){&nbsp; &nbsp; &nbsp; &nbsp; $str=$shopProduct->title . ":" . $shopProduct->getProducer()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; . " (".$shopProduct->price.")\n";&nbsp; &nbsp; &nbsp; &nbsp; print $str;&nbsp; &nbsp; }}$product1 = new ShopProduct("My Antonia", "Willa", "Cather", 5.99);$writer = new ShopProductWriter();$writer->write($product1);
打开App,查看更多内容
随时随地看视频慕课网APP