我正在尝试调用一个名为displaySentence()的函数,并将其输入“candy”的值输入到candycontest.php的表单中。该函数最终将具有更多功能,但是现在我只是想要回显该句子的值以确保函数正常工作。当我运行脚本时,页面会显示,直到它进入我的功能,此时它是空白的。
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>
答案 0 :(得分:1)
将$magicSentence = new MagicSentence("The cow jumped over the moon.");
更改为$magicSentence = new Ticket("The cow jumped over the moon.");
您需要这样做,因为displaySentence()
类(延伸到Ticket
类)下存在MagicSentence
方法。
另外,将displaySentence();
更改为$magicSentence->displaySentence();
以便调用您的方法。你不能像普通函数一样调用方法。
那样做,你应该是金色的。
答案 1 :(得分:0)
创建类Ticket
,$ticketObj
的对象,并使用$ticketObj->displaySentence();
代替displaySentence();
答案 2 :(得分:0)
displaySentence();
是Ticket
类的一种方法,您从未实例化过某个对象,因此它在任何上下文中都不存在。
$magicSentence = new MagicSentence("The cow jumped over the moon.");
需要是:
$magicSentence = new Ticket("The cow jumped over the moon.");
和
displaySentence();
需要:$magicSentence->displaySentence();