Timothy Coetzee Timothy Coetzee - 2 years ago 161
PHP Question

Undefined variable in creating new object error with constructor

I am a 2nd Year IT student just started with OOP in PHP and i'm really struggling to get the hang of it, I have been coding in a procedural way for years so please understand making the switch to OOP is extremely challenging, and I am yet to see the benefit of it, anyway just had to get that of my chest.

enter image description here
enter image description here
enter image description here
enter image description here

According to the above question I came above with the above code,, which I tweaked to infinity, my prescribed book is also not very helpful


class Registration{
private $user_type;
private $user_name;

function __construct($user_type, $user_name){

function setUser($user_type, $user_name){
if($user_type == "admin"){
$user_name = "Peter";
$msg = "Hi administrator ".$user_name;
else if($user_type="member"){
$user_name = "Ntubele123!";
$msg = "Hi member ".$user_name;

function getUser(){
return $this->user_type;
}//function getter


$userInfo = new Registration($user_type, $user_name);
$user = $userInfo->setUser("admin", "Peter");
$user = $userInfo->getUser();


  • I suspect a lot is wrong with the above code, if someone could be kind enough to let me know where I am going wrong and what I should consider changing, keeping beginner friendly in mind, it would be greatly appreciated.


Undefined variable user_type & user_name

Answer Source
$userInfo = new Registration($user_type, $user_name);

In this line $user_type, $user_name is undefined because no variables declared with this name

So declare the variable at first than create object of Registration class

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download