简体   繁体   中英

OOP PHP not working, the web page returns nothing>

I'm trying my first OOP PHP, but I seem to have hit a wall. As far as i can see there is nothing wrong with the code, and i get no error message. Thanks already!

<?PHP
class President {
    public $lastname;
    public $dob;
    public $dod;
    public $firstlady;
    public $wikipage;
    public $display;
    public $party;
    public $inoffice;

    public function __construct ($name, $dob, $dod, $girl, $wiki, $pic, $party, $terms){
        $this->lastname = $name;
        $this->dob = $dob;
        $this->dod = $dod;
        $this->firstlady = $girl;
        $this->wikipage = $wiki; 
        $this->display = $pic;
        $this->party = $party;
        $this->inoffice = $terms;
    }

    public function Write(){
        return "President". $name . "was in office for" . $terms . "." . "He was born on" . $dob . "and" . $dod . "." . "He represented the" . $party . "and lived in the Whitehouse with his wife" . 
        $girl . "<br/>" . "<img src'" . $pic . "' />" . "<br />" . "<a href'" . $wiki . "'> Read more on Wikipedia</a>";
    }
}

$obama = new President();
$obama->Write('Obama', 'June First 1992', 'is still alive', 'Michelle Obama', 'http://www.google.com', 'www.google.com/', 'Democrat', 'Two Terms');
echo $obama;

?>

first, turn on error reporting... then..

2 problems that I can see.

Firstly, youre constructor is expecting lots of parameters, which you are not passing when you instantiate the object, but when you call the Write method, which isnt expecting anything.

Then, you dont echo $obama->Write(..) when it returns a string.

solution:

$obama = new President('Obama', 'June First 1992', 'is still alive', 'Michelle Obama', 'http://www.google.com', 'www.google.com/', 'Democrat', 'Two Terms');
echo $obama->Write();

should work assuming that your parameters are right in your construct.

edit

as stated in comments below, your write method wont be able to access any of the class vars as its only looking at the local scope. You need to change your variable calls like this:

return "President". $name

to

return "President". $this->name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM