Variable declaration in classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Variable declaration in classes

Post by Steveo31 »

Is it needed? Like so:

Code: Select all

class Member {
    
    //member variables
    var $username;
    var $password;
    var $first;
    var $last;
    var $email;
    var $registerDate; 
    var $interests;
    var $profile;
    var $estore;
    var $pageDir;
    var $memberLevel;
    var $mailingList;
    
    function setVars(){
        //...
    }
}
Or will it work when you do $classVar->setVars($value)..
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

class variables work just like regular php variables

$this->foo = 'foo';

if $foo hasnt been declared, it will be created

and if you create it inside a class function, it will still work like as if you had declared it.


but imo its a bad habit not to declare them first. declaring them imo mkaes the class more readable and easier to see whats being done.

espescially if you declare them and set thier initial values or just an empty value to set the type

Code: Select all

class FOO {
    var $foos = array(); // i know $foos will be used as an array now, 
    var $bar = ''; //string


}
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

Ah ok, cool. Thanks :) Makes great sense.
Post Reply