Home > Enterprise >  How to print values of a form after getting input in php
How to print values of a form after getting input in php

Time:02-11

I want to show the input values after getting the input. I am using the PHP OOP concept. I want to access the variables " name " and " email" via object and then prints values

<h1>HTML Form</h1>
<form method="post" action="index.php">
    Name: <input type="text" name="name"><br><br/>
    Email: <input type="text" name="email"><br/>
    <br/>
    <input type="submit" name="submit" value="Submit" />
</form>
<?php

class Registration{
     public $name; 
     public $email;

     public function setName(){
    this->name= $_GET['name'];

     }

     public function setEmail(){
         $this->email= $_GET['email'];
     }

}// class ends here
$obj=new Registration;
echo $obj->name;

?>

CodePudding user response:

Try this:

class Registration{
     public $name; 
     public $email;
     
    //you can give class variables values in the constructor
    //so it'll be setted right when object creation
    function __construct(){
        $this->name = $_POST['name'];
        $this->email = $_POST['email'];
    }
    

}// class ends here
if($_POST){

    $obj=new Registration;
    echo $obj->name;
    echo $obj->email;
}

CodePudding user response:

You have to call your function.

$obj=new Registration;
echo $obj->name;

Here $obj->name is empty, you never passed in your function setName().

Try with :

$obj=new Registration;
$obj->setName();
echo $obj->name; 

(And $this->name= $_GET['name']; instead of this->name= $_GET['name'];)

  • Related