9

I have the following code (I'm a Dot Net developers and I thought if I can bring my OOP knowledge to PHP)

class user {
    var $_un;
    function user($un) {
     $_un = $un;
    }
    function adduser() {
    }
    function checkuser() {
    }
    function printuser () {
        echo $_un;
    }
}

$newuser = new user('Omar Abid');
$newuser->printuser();

So the problem is simple "$_un" is empty!! I want it to be filled, when the class is created using the constructor and then saved.

I used to do that in C# .net, but here it doesn't work for some reasons. Thanks!

4 Answers 4

10

Rather than user() you should use __construct(), it's the preferred way to add a Constructor in PHP5. Also consider to add visibility to your methods and members (public / protected / private)

public function __construct($un) {
    $this->_un = $un;
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you have 20 variables for example, would you have to list them as arguments in the __construct(var1, var2, etc) ?
7

In order to access class members in PHP you need to use $this-> .

So what you're currently doing is declaring a local variable called $_un, rather than assigned to the member variable $this->_un .

Try changing your code to:

function user($un) {
 $this->_un = $un;
}

function printuser () {
    echo $this->_un;
}

And it should work.

1 Comment

the other function should changes also function printuser () { echo $this->_un; } Thanks it's working correctly now
3

in php you have to use $this to access variables (or methods) of the current class, this is necessary to distinguish class members from local variables

Comments

2

Use this construct.

class user {    
  var $_un;    
  function user($un) 
   {
      $this->_un = $un;    
    }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.