I am trying to call a function called displaySentence() and have it output the value of the 'sentence' typed into the form on candycontest.php. The function will eventually have more features, but for now I am just trying to echo out the value of that sentence to ensure the function works. When I run the script, the pages displays until it gets to my function, at which point it is blank.
candycontest.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pete's Treats Candy Contest</title>
</head>
<body>
<form action="checkticket.php" method="post">
<label for="ticketNum">Enter your ticket number:</label>
<input type="number" name="ticketNum" style="width:100px"><br/>
<label for="sentence">Enter the magic sentence:</label>
<input type="text" name="sentence" style="width:600px"><br/>
<input type="submit" value="Am I a Winner?">
</form>
</body>
</html>
checkticket.php
<?php
$userTicket = $_POST['ticketNum'];
class MagicSentence {
public $sentence;
public function __construct($sentence) {
$this->setSentence($sentence);
}
public function getSentence() { return $this->sentence; }
public function setSentence($sentence) {
$this->sentence = $sentence;
}
} // End class MagicSentence
class Ticket extends MagicSentence {
public $ticketNum;
public function displaySentence() {
$userSentence = $_POST['sentence'];
echo $userSentence;
}
}
$magicSentence = new MagicSentence("The cow jumped over the moon.");
?>
<html>
<head>
<meta charset="utf-8">
<title>Pete's Treats Candy Contest</title>
</head>
<body>
<?php
echo 'Your ticket number is: ' . $userTicket . "<br>";
echo 'The magic sentence is: ' . $magicSentence->getSentence() . "<br>";
displaySentence();
?>
</body>
</html>
Change $magicSentence = new MagicSentence("The cow jumped over the moon.");
to $magicSentence = new Ticket("The cow jumped over the moon.");
You need to do this because the displaySentence()
method exists under the Ticket
class (which extends off the MagicSentence
class).
Also, change displaySentence();
to $magicSentence->displaySentence();
in order to call your method. You cannot call a method as you would a regular function.
Do that and you should be golden.
Create an object of class Ticket
, $ticketObj
and use $ticketObj->displaySentence();
in place of displaySentence();
displaySentence();
is a method of the Ticket
class, of which you never instantiated an object, so it doesn't exist in any context yet.
$magicSentence = new MagicSentence("The cow jumped over the moon.");
needs to be: $magicSentence = new Ticket("The cow jumped over the moon.");
and displaySentence();
needs to be: $magicSentence->displaySentence();