skip to Main Content

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


  1. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search