theJava
theJava

Reputation: 15034

Few questions in accessing a class?

<?
class Contact {

    //protected $message = "Hello World";

    function __construct($message){
        echo $this ->message;
    }

    function getName() {

    }

}

$con = new Contact("Hello World");    

?>

<form method="post" action="Contact.php">
  1. When i compile this class, its not printing "Hello World" Why?
  2. How can i call the getName() function in my form action. Is the below right way.

<form method="post" action={$con->getName()}>

Upvotes: 0

Views: 47

Answers (1)

SeanCannon
SeanCannon

Reputation: 77956

A) You don't compile PHP

B) $message isn't an instance variable, it's a parameter:

function __construct($message){
    echo $message;
}

The way you inject your PHP method calls into HTML:

<form method="post" action="<?php echo $con->getName(); ?>">

Your commented out //protected $message = "Hello World" is on the right track. Something like this would be ideal:

class Contact {

    protected $message = "Hello World";

    function __construct($message = null){
        $this->setMessage($message);
    }

    public function getMessage(){
        return $this->message;
    }

    public function setMessage($message = null){
        if($message !== null){
            $this->message = $message;
        }
    }
}

Used like so:

$con = new Contact();
$con->getMessage(); // "Hello World;
$con->setMessage("Goodbye World");
$con->getMessage(); // "Goodbye World"

$con2 = new Contact("Goodbye World"); 
$con2->getMessage(); // "Goodbye World"

Upvotes: 3

Related Questions