1

我是 php 的 OOP 概念的新手。我做了一个这样的类

<?Php
  class ShopProductWriter {
    public function write( $shopProduct ) {
    $str = "{$shopProduct->title}: " .
            $shopProduct->getProducer() .
           " ({$shopProduct->price})\n";
    print $str;
    }
  }

  $product1 = new ShopProduct( "My Antonia", "Willa", "Cather", 5.99 );
  $writer = new ShopProductWriter();
  $writer->write( $product1 );
?>

在这里,我收到了错误,就像Fatal error: Class 'ShopProduct' not found in line 11实际上我正在从教程中做这个示例一样。有人可以告诉我错误的部分在哪里。我已经完全像教程一样。

4

2 回答 2

2

您还需要像这样定义 ShopProduct 类:

class ShopProduct 
{
    public $title;
    public $price;        

    public function __construct( $title, $value1, $value2, $price)
    {
        $this->title = $title;
        $this->price= $price;
    }
}
于 2012-07-06T06:07:00.180 回答
1

您创建了类 ShopProduct 的新实例,尽管您没有定义它。您只声明了 ShopProductWriter 而没有声明 ShopProduct。这就是为什么$writer = new ShopProductWriter();有效和$product1 = new ShopProduct( "My Antonia", "Willa", "Cather", 5.99 );无效的原因。

于 2012-07-06T06:06:08.650 回答