tags:

views:

57

answers:

1

Hello everybody, here's my problem:

$Me[1] = new User(1);
$Me[2] = new User(2);
$Me[3] = new User(19);
$Me[4] = new User(75);
$Me[5] = new User(100);
foreach ($Me as $k) echo $k->getId();

I'm trying to create 5 users with, of course, different ID. The problem is that the User with ID 2 'overwrite' the User with ID 1, the User with ID 3 'overwrite' the User with ID 2, the User with ID 4 'overwrite' the User with ID 3, the User with ID 5 'overwrite' the User with ID 4.

I don't really know how to fix this, can anybody please help me?

Thanks in advance for your help!


I can't get the $id from the parent class. It seems like the last class initialized "overwrite" all the values (maybe becouse I declared it static? but how can I get it?)..

This is my class:

class User {
    public static $id;

    public function __construct($id) {
        $this->id = $id;
    }

    public function getId() {
        return $this->id;
    }
}

class Sub extends User {
    public function __construct($id) {
    }

    public function printUserLink(){
            echo '<a href="userprofile.php?userid='.parent::getId().'">Go to user profile</a>';
    }
}

How do I get the Id in the "Sub" class?

A: 

It's likely that the problem lies in your User class. This simple example works as expected:

class User {
    private $id;

    public function __construct($id) {
        $this->id = $id;
    }

    public function getId() {
        return $this->id;
    }
}

$Me[1] = new User(1);
$Me[2] = new User(2);
$Me[3] = new User(19);
$Me[4] = new User(75);
$Me[5] = new User(100);

foreach ($Me as $k) echo $k->getId() . "\n";

Outputs:

1
2
19
75
100

Without details of your User class (as suggested by ircmaxell), resolving the problem will be tricky.

Mike
I can't get the $id from the parent class. It seems like the last class initialized "overwrite" all the values (maybe becouse I declared it static? but how can I get it?)..This is my class:class User { public static $id; public function __construct($id) { $this->id = $id; } public function getId() { return $this->id; }}class Sub extends User { public function __construct($id) {} public function printUserLink(){ echo '<a href="userprofile.php?userid='.parent::getId().'">Go to user profile</a>'; }}How do I get the Id in the "Sub" class?
Yes, it will be because you have declared it as static (see [Static Member Variables](http://www.brainbell.com/tutorials/php/Static_Member_Variables.html) for an use of static member variables). Why do you need it declared as static?
Mike
Becouse I don't know how to access it from a subclass (parent::$var doesn't work..) How can I do?