Page 1 of 1

php classses

Posted: Sun May 10, 2009 9:15 am
by sasa1985
how to pass a value to variable inside a class?

i need pass username which was eccepted from a user to the variable $pass inside the class test. this is the code i've tried so far

Code: Select all

 
 <?php
class Example {
    /////////////////////variables//////////////
    var $user ;
    var $pass ;
 ////////////setters & getters //////////////////       
    function set_user($usr)
    {
    
    $this-> user= $usr;
    
    }
    
    function get_user()
    {
    return $this-> user;
    }
    
    
    function set_pass($pas)
    {
    
    $this-> pass= $pas;
    
    }
    
    function get_pass()
    {
    return $this-> pass;
    
    }
    
/////////////////////////////////////////////////   
    
    
    function foo() {
        echo "foo!\n";
    }
    
}
 
// create an Example object
$e = new Example();
 
 
echo $e->get_user(); 
echo $e->foo();
echo $e->get_pass();
 
?>
 
can anybody help me with this please

Re: php classses

Posted: Sun May 10, 2009 9:29 am
by greyhoundcode

Code: Select all

class Example 
{
    var $pass;
 
    /*
     * Rest of your code in here ...
     */ 
}
 
// create an Example object
 
$e = new Example();
$e->pass = $user_password;
Of course you may wish to implement a setter method, but (someone correct me if I'm wrong!) to enforce getting/setting of properties like that you would probably need to write in PHP 5. You might also set your user and pass members via a constructor:

Code: Select all

class Example 
{
    var $pass;
    var $user;
 
    function Example($user, $pass)
    {
        $this->pass = $pass;  // Validate the values
        $this->user = $user;  // first of course!
    }
    /*
     * Rest of your code in here ...
     */ 
}
 
// create an Example object
 
$e = new Example($username, $userpass);