1

please point out the obvious as I just started learning about OOP in PHP. My class books contains two public functions: one to display a request books form, and the other to submit the book details to my database. I use two if statements to call these functions when the user clicks the request book or submit form buttons.

Here is my class:

class Book
{
    public $title;
    public $author;
    public $id;

    public function SendToDatabase()
    {
        echo "inside SendToDatabase";
    }

    public function Display()
    {
        echo "<form action='' method='post'>
    Title: <input type='text' name='title'><br>
    Author: <input type='text' name='author'><br>
    <input type='submit' name='submitBook' value='submit'>
    </form>";
    }

}

And here is my code to call the functions using buttons (in the same file). As is, the SendToDatabase() function is never called. I am able to get it working when I combine the if statements, but then the buttons would not work properly. I am a little confused because I thought the scope of the object is the same across if statements. I would really appreciate anyone pointing out my mistake. Cheers.

echo "<form action='' method='post'><input type='submit' name='submit' value='Request Book'></form>";
$request = $_POST['submit'];
$submit  = $_POST['submitBook'];
if ($request) {
    $book = new Book();
    $book->Display();
}

if ($submit) {
    $book->SendToDatabase();
}

1 Answer 1

6

You need to define what $book is in both cases, so get the assignment out of the first if block:

$book = new Book();
if ($request) $book->Display();
if ($submit) $book->SendToDatabase();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.