Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

PHP OOP Mid-Challenge Task 5 Not Working

I can't seem to get my task 5 to work in the PHP OOP Mid-Challenge. Here is my code. Any suggestions? Thanks!! Bojana

<?php

class Fish { public $common_name; public $flavor; public $record_weight;

function __construct($name, $flavor, $record) { $this->common_name = $name; $this->flavor = $flavor; $this->record_weight = $record; }

$bass = new Fish(); $bass->common_name = "Largemouth Bass"; $bass->flavor = "Excellent"; $bass->record_weight = "22 pounds 5 ounces";

public function getInfo() { return "A " .$this->common_name . "is an " .$this->flavor . "flavored fish. The world record weight is" .$this->record_weight; } } echo $bass->getInfo(); ?>

1 Answer

You are creating your $bass inside the definition of the Fish() class. If you move it out of the class definition, the object will be created. So for example:

<?php
class Foo() {
   $bar = new Foo();
}

This attempts to add a new fish to the description of the class. If you instead do:

<?php
class Foo() {

}
$bar = new Foo();

the object will be created as a new instance of the class.

Here's how this would look in your code:

<?php

class Fish {
    public $common_name;
    public $flavor;
    public $record_weight;

    function __construct($name, $flavor, $record) {
        $this->common_name = $name;
        $this->flavor = $flavor;
        $this->record_weight = $record;
    }

    // this is where the new Fish() used to be

    public function getInfo() {
        return "A " .$this->common_name . "is an " .$this->flavor . "flavored fish. The world record weight is" .$this->record_weight;
    }
}
// Move the class initialization down here!
$bass = new Fish();
$bass->common_name = "Largemouth Bass";
$bass->flavor = "Excellent";
$bass->record_weight = "22 pounds 5 ounces";

// No need to echo, it just wants you to define the getInfo function. I have commented the echo out.
//echo $bass->getInfo();

?>

Many thanks for your detailed explanation, Joe! I didn't realize that we have to instantiate object outside of the class declaration. Now my code works :)