Jump to content

Kell

New Members
  • Posts

    2
  • Joined

  • Last visited

Posts posted by Kell

  1. Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble if the price of a book is less than $20.00 output the book’s name and price if the book’s title comes after the letter R in the alphabet output the book’s title.

    I am getting these error:

    Notice: Trying to get property 'price' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 45

    Notice: Trying to get property 'title' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 49

    Notice: Trying to get property 'price' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 50

    Fatal error: Uncaught Error: Call to a member function get_first_char() on string in C:\xampp\htdocs\PHP objects\books.php:52 Stack trace: #0 {main} thrown in C:\xampp\htdocs\PHP objects\books.php on line 52

    My code is:

    <?php
    class Book {
      // Properties
      public $price;
      public $title;
      public function get_first_char() {
        $titleArray = str_split($this->title);
        return reset($titleArray);
    }

      // Methods
      function set_price($price) {
        $this->price = $price;
      }
      function get_price() {
        return $this->price;
      }
      function set_title($title) {
        $this->title = $title;
      }
      function get_title() {
        return $this->title;
      }
      
    }

    $first_book = new Book();
    $first_book->set_price('$13.95');
    $first_book->set_title('Moby Dick');
    echo "Price: " . $first_book->get_price();
    echo "<br>";
    echo "Title: " .  $first_book->get_title();
    echo "<br>";
    $second_book = new Book();
    $second_book->set_price('$23.99');
    $second_book->set_title('Wuthering Heights');
    echo "Price: " . $second_book->get_price();
    echo "<br>";
    echo "Title: " .  $second_book->get_title();
    echo "<br>";
    $book = array("Moby Dick", "Wuthering Heights");
    echo "Book Titles: " . $book[0] . ", "  . " and " . $book[1] . ".";

    foreach ($book as $bookItem) {
        $price = $bookItem->price;
        // Right now $price is a string ('$xx.xx'), we need it to be numeric
        $price = (float) substr($price, 1);
        if ($price < 20) {
            echo $bookItem->title;
            echo $bookItem->price;
        }
        if (ord(strtoupper($bookItem->get_first_char())) > ord('R')) {
            echo $bookItem->title;
        }
    }
     ?>

    Any help will be very much appreciated

    Thank you

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.