简体   繁体   中英

Using the object operator in PHP

I looked at this post to try and understand the object operator better: Where do we use the object operator "->" in PHP?

But when I copied and pasted the php in the 2nd response, I just get a blank page when I run it. Here is my code:

PHP:

<?php

    class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$a = new SimpleClass();
echo $a->var;
$a->displayVar();

?>

HTML:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>

        <form action ="process.php" method ="POST">
            First Name: <input type="text" name="fName"> 

            <input type="submit">       
        </form>

        <p>
            Click for objectOperator.php
            <button onsubmit="objectOperator.php">Submit</button>
        </p>
    </body>
</html>

Ignore the form in the HTML, that was for something else I was doing. When I click on the Submit button I want to run the php in objectOperator.php (which is the name of my php file). But when I click it nothing happens.

You can try this

I just tried this on phpfiddle and it was working

<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';

// method declaration
public function displayVar() {
    echo $this->var;
}
}

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$a = new SimpleClass();
echo $a->var;
$a->displayVar();
}
?>


<form action ="" method ="POST">First Name: <input type="text" name="fName"> 
<input type="submit">       
</form>

The key is to have the correct action

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