tags:

views:

37

answers:

2

Is it allowed to implicitly assign instance variables to an instance? That is, inside a method of a class that has no instance variables, can I just do this?

$this->foo = "foo";
$this->bar = "bar";

and later just call those again? Will PHP just create instance variables in this case?

+1  A: 

Yes, it will just create new properties on the object.

Nicolás
This isn’t good practice though; it leaves out documentation from the class code and makes the new properties public.
Ciarán Walsh
But useful when you're writing an template engine :-)
openfrog
+1  A: 

Yes. PHP will simply create any member variables that are referenced but have not been declared. I just tested it with the following code:

<?php
class Test {
    public function __construct() {
    }

    public function setMembers() {
        $this->foo = "fooValue";
        $this->bar = "barValue";
    }

    public function echoMembers() {
        echo $this->foo . "\n";
        echo $this->bar . "\n";
    }
}

$test = new Test();
$test->setMembers();
$test->echoMembers();
?>

When executed, this outputs:

fooValue
barValue

Which proves that this works. I still recommend declaring all class member variables at the top of the class. It's what the OO programmers maintaining your code will expect to see.

FYI: I ran my test with the following version of PHP:

$ php -version
PHP 5.2.8 (cli) (built: Feb  5 2009 21:21:13) 
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
Asaph
no need to declare at the top level, php is not that strict and it is not required.
dusoft