Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 :)