php classses

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
sasa1985
Forum Newbie
Posts: 1
Joined: Sun May 10, 2009 9:02 am

php classses

Post 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
Last edited by Benjamin on Sun May 10, 2009 12:41 pm, edited 1 time in total.
Reason: Added [code=php] tags.
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: php classses

Post 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);
Post Reply