Based on construct create or delete some methods
Based on constructor of the class. create or destroy new methods. I often requires based on construct to disable or destroy methods within the class. Can any one help me out?
class Test
{
function __construct(userID)
{
if(!isValidUser($userID))
{ destroy(methods); }
}
function addPost()
{
}
}
Once destroy is called. The methods or selected methods should be destroyed
Hope you understand t开发者_运维百科his time.
You can use the factory pattern to create an instance of a subclass of the class. Each subclass has the methods it needs. The superclass only has the methods every subclass needs.
class User
{
function foo(){}
function foo1(){}
static function constructUser()
{
if(self::isValidUser())
{
return new ValidUser();
}
else
{
return new User();
}
}
static function isValidUser()
{
//...
}
}
class ValidUser extends User
{
function addItem(){}
}
$user = User::constructUser();
I have the feeling that you are in need of the Factory pattern: an object (or function) that creates objects of different types, depending upon it's arguments.
Because what you really do when defining a different set of methods, depending on the user, is creating objects of another type: an AuthenticatedUser
object vs. a NonAuthenticatedUser
.
Using a constructor of ClassX for that is really not a good approach.
class User { // with common methods
}
class ValidUser extends User {
function onlyForValid() {}
}
class InvalidUser extends User {
function onlyForInvalid() {}
}
function createObject( $id ){
if( isValidUser( $id ) ) return new ValidUser( $id );
else return new InvalidUser( $id );
}
There is no way to disable or destroy functions in PHP. You can approach this from the opposite end, however. That is, only create the functions if appropriate (i.e. using create_function()) within the constructor. Alternately, you can use a superclass and extend it using a subclass that only extends the functions that subclass needs. If you would like further illustration I can post an example for you.
精彩评论