tags:

views:

32

answers:

1

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

+3  A: 

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;
?>
HCL
Stack Overflow takes the start and end php tags out by default :) Thanks you solved my little problem didn't realise the issue with $this and returning variables
wiggles