How do i create an array where deconstructed or deleted objects are saved in. I wrote the code below but it doesnt work.The goal is to add usernames of deconstructed users into the array deletedUsers.
//Class User
class User
{
//User attributes
public $firstname;
public $lastname;
protected $username;
protected $registerdate;
public $deletedUsers = array();
//Constructor
public function __construct($firstname, $lastname)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->username = "$firstname.$lastname" . rand(1, 100);
$this->registrdate = date("d.m.Y");
}
public function __destruct()
{
$this->deletedUsers[] = $this->username;
return implode(", ", $this->deletedUsers);
echo "User has been deleted";
}
public function getInfo()
{
return $this->firstname . " " . $this->lastname . " " . $this->username . " " . $this->registredate;
}
public function getDeletedUsers()
{
$dUsers = implode(", ", $this->deletedUsers);
return $dUsers;
}
}
$user1 = new User("John", "Smith");
echo $iser1->getInfo();
echo "<br>";
unset($user1);
echo $user1->getDeletedUsers();
2
Answers
The fourth line,
unset($user1);
is destroying the User object you created, so you can’t displaydeletedUsers()
from that object. What you want instead is aUsers
class that contains all users, deleted and active.Static properties can be used for this purpose