wiggles
wiggles

Reputation: 499

When I work with PHP classes nothing happens

Below is some code I've been trying, and I've messed about with it to include die()'s and echo()'s here and there but nothing happens, if I try running someone else's class code with instances of the objects it works fine, but I can't see what's wrong with my code.

class Form {

    private $form_method; 

    public function __construct() 
    {
        $form_method = '';      
    } 

    public function setFormMethod($method) 
    {
        $this->$form_method=$method;    
    }

    public function getFormMethod()
    {
        return $this->$form_method; 
    } 

} 

$newForm = new Form();
$newForm->setFormMethod('POST');
$var = getFormMethod();

echo $var;

I am running PHP 5.3.2 on a localhost through XAMPP by the way.

Any help appreciated

Upvotes: 1

Views: 148

Answers (1)

HCL
HCL

Reputation: 196

There are a few things that I see. First is that you should not include $ with your variable names when you refer to them using "this".

Example: Change

return $this->$form_method; 

To

return $this->form_method;

The call to getFormMethod() will also not work, since the code refers to a method outside the class.

Change

$var = getFormMethod();

To

$var = $newForm->getFormMethod();

As Catfish suggests, you may also be missing the php tags (unless you just posted an extract)

This code should work (untested)

<?php
class Form {

    private $form_method; 

    public function __construct() 
    {
        $this->form_method = '';      
    } 

    public function setFormMethod($method) 
    {
        $this->form_method = $method;    
    }

    public function getFormMethod()
    {
        return $this->form_method; 
    } 

} 

$newForm = new Form();
$newForm->setFormMethod('POST');
$var = $newForm->getFormMethod();

echo $var;
?>

Upvotes: 3

Related Questions