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();
CodePudding user response:
Static properties can be used for this purpose
class User
{
//User attributes
public $firstname;
public $lastname;
protected $username;
protected $registrdate;
protected static $deletedUsers = [];
//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()
{
self::$deletedUsers[] = $this->username;
echo "User has been deleted";
}
public static function getDeletedUsers()
{
return implode(", ", self::$deletedUsers);
}
public function getInfo()
{
return $this->firstname . " " . $this->lastname . " " . $this->username . " " . $this->registrdate;
}
}
$user1 = new User("John", "Smith");
echo $user1->getInfo();
echo "<br>";
unset($user1);
echo User::getDeletedUsers();
CodePudding user response:
The fourth line, unset($user1);
is destroying the User object you created, so you can't display deletedUsers()
from that object. What you want instead is a Users
class that contains all users, deleted and active.
$user1 = new User("John", "Smith");
echo $user1->getInfo();
echo "<br>";
unset($user1);
echo $user1->getDeletedUsers();