Alexander Jung
Alexander Jung

Reputation: 1

php constructor, Object attribute can't be output

I started with php a bit ago, doing a website for my university, but for some reason i can't get my constructor to work.

User.class.php

class User {

public $id="";
public $name="";
public $vorname="";
public $matrikelnummer="";
public $status="";
public $wl_platz="";
public $modul="";
public $versuch="";

public function __construct($id, $name, $vorname, $matrikelnummer, $status, $wl_platz, $modul, $versuch) 
{
    $this->$id=$id;
    $this->$name=$name;
    $this->$vorname=$vorname;
    $this->$matrikelnummer=$matrikelnummer;
    $this->$status=$status;
    $this->$wl_platz=$wl_platz;
    $this->$modul=$modul;
    $this->$versuch=$versuch;
}

in main.php

include_once('include/User.class.php');         
$user=new User($id, $name, $vorname, $mn, $status, $wl_platz, $modul, $versuch);

the variables in the call are strings that were set before, obviously

if i do echo serialize($user);

i get

O:4:"User":16:{s:2:"id";s:0:"";s:4:"name";s:0:"";s:7:"vorname";s:0:"";
s:14:"matrikelnummer";s:0:"";s:6:"status";s:0:"";s:8:"wl_platz";
s:0:"";s:5:"modul";s:0:"";s:7:"versuch";s:0:"";s:1:"1";s:1:"1";s:9:
"alexander";s:9:"alexander";s:4:"jung";s:4:"jung";s:5:"34525";s:5:"34525"
;s:19:"registered for exam";s:19:"registered for exam";
s:4:"TODO";s:4:"TODO";s:3:"PAD";s:3:"PAD";s:1:"3";s:1:"3";}

so it just be some sort of working, but if i do echo $user->name; i get empty output. pretty sure there must be a small mistake somewhere, but can't find it... (and i did some searching and all)

Upvotes: 0

Views: 38

Answers (1)

Yupik
Yupik

Reputation: 5031

You're not setting your attributes by $this->$id.

It's like you're setting $this->yourvalueunder$id = ...

Change this:

public function __construct($id, $name, $vorname, $matrikelnummer, 

$status, $wl_platz, $modul, $versuch) 
{
    $this->$id=$id;
    $this->$name=$name;
    $this->$vorname=$vorname;
    $this->$matrikelnummer=$matrikelnummer;
    $this->$status=$status;
    $this->$wl_platz=$wl_platz;
    $this->$modul=$modul;
    $this->$versuch=$versuch;
}

To this:

public function __construct($id, $name, $vorname, $matrikelnummer, $status, $wl_platz, $modul, $versuch) 
{
    $this->id=$id;
    $this->name=$name;     // '$' sign in attribute name
    $this->vorname=$vorname;
    $this->matrikelnummer=$matrikelnummer;
    $this->status=$status;
    $this->wl_platz=$wl_platz;
    $this->modul=$modul;
    $this->versuch=$versuch;
}

Upvotes: 2

Related Questions