Page 1 of 1
Class staticism...
Posted: Sat Feb 07, 2009 9:39 am
by BETA
This may be a noob question but i've struggling with it a bit...

Can I make a class which is static and non-static at the same time? I mean if it can work instantiated and non-instantiated.
I've tried to do so... but it seems that some things don't work properly I don't know if its because of the use of self:: in my functions...
So the question is: Can I or do i have to decide if I want my class to be static or non-static? And if i can... What am I doing wrong?
Thx in advance!
(P.S:If u need some of my code to answer let me know...)
Re: Class staticism...
Posted: Sat Feb 07, 2009 10:21 am
by mickeyunderscore
You can declare some methods static and others not yes, however you won't be able to use static methods in object context. Static can only be used in class context. The singleton design pattern makes use of this with a static getter method to get the current instance.
Code: Select all
class StaticMethods{
public static function doSomething(){
self::privateStaticFunction();
}
private static function privateStaticFunction(){
return 1;
}
public function getTrue(){
return true;
}
}
StaticMethods::doSomething(); //call static method in class context
$static = new StaticMethods(); //instantiate object
$static->getTrue(); //call object method
$static->doSomething(); //this works but is a bug, see note
$static::doSomething(); //parse error
Note: Don't rely on this functionality as this is a bug in PHP:
http://bugs.php.net/bug.php?id=27304
Re: Class staticism...
Posted: Sat Feb 07, 2009 11:32 am
by BETA
ok so if i remove the static keyword will I be able to use instantiation and be able to call it like class::property/method too?
Cause if that's what u mean I tried removing static but it doesn't seem to do anything...
Maybe i expressed the concept badly... what i want is that i can call my functions and methods like this:
$classinstance->method/property;
and this class::method/property;
both ways...
Well thx anyway!
Re: Class staticism...
Posted: Sat Feb 07, 2009 11:50 am
by mickeyunderscore
You can't do that. Methods are either available through object context (normal declaration) or they are available in class context (static declaration). The point of a static method/attribute is that it is accessible in class context, and cannot be modified when the class is instantiated.
Do you mind me asking exactly why you want/need methods available in both contexts?
Re: Class staticism...
Posted: Sat Feb 07, 2009 12:18 pm
by BETA
Ok so that's all i wanted to know...
No i don't mind at all... I'm making a class i think will realease under GNU/GPL and i just wanted to know if i could do it so developers and people who used the class could either instantiate the class or use it statically...
So then I have to choose if i want my users to isntantiate or use it statically, haven't I?
Well thx for ur help ^^