Jump to content

problem with extends (or my class design)


leeming

Recommended Posts

Basically i am wanting to have an extra area of a class (kinda like a module) kind of like

 

class user
{
}

class admin extends user
{
}

 

but if i use the user class, and later in my code i find out the user is an admin, i create a new object admin... but there is my problem. This will be a new object, and thus all the methods in the user class will need to be set up again. Is there a way to add on this extended class to the current object (the same object)

 

The original solution i thought of was this:

 

 

class user
{
  .. user functions etc

  function isStaff()
  {
    //set true or false
  }

  if($this->isStaff())
  {
     //extra staff functions
  }
}

 

but obviously this did not work, and the only other way around this would be to add to each staff function

 

 

if(!$this->isStaff()) 
   return FALSE;

 

 

 

which honestly would look very messy, and due to this been quite a large class would get VERY messy and confusing very fast.

Link to comment
https://forums.phpfreaks.com/topic/52995-problem-with-extends-or-my-class-design/
Share on other sites

  • 3 weeks later...
class user
{
// user methods
}

class admin extends user
{
/* since admin has the capabilities and methods of a normal user in addition to admin capabilities, we should extend admin from user to inherit all the  methods. This is to save code.*/
// additional admin methods
}


/* You cannot just insantiate a user object before checking for the status. Doing this means that you will need to create a new object for the admin. And I don't think you can add an 'if' statement in the class, you will need to place it in one of the methods. One way is to do your checking like this:
*/

if(user_is_staff) {
$user = new admin;
}
else {
$user = new user;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.