Forum Moderators: coopster

Message Too Old, No Replies

static variables in classes

         

blackeagle2

1:30 pm on Jul 17, 2006 (gmt 0)

10+ Year Member



Hi everyone!

I have a problem with static variables in php. How do I access static variables in the super class that are declared in the child?

class SuperClass
{
public static function connect()
{
echo $user;
}
}

class ChildA
{
private static $user = 'John'
}

class ChildB
{
private static $user = 'Smith'
}

This does not seem to work
Thanks for help

RonPK

2:57 pm on Jul 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Are you sure this has to do with the use of static?

My 2 cents:
1. the child-classes should be extensions of the main class:

class ChildA extends SuperClass

2. the static variables should be declared as
protected. private
limits their scope to the class that declares them.

blackeagle2

9:21 pm on Jul 17, 2006 (gmt 0)

10+ Year Member



yes of course I forgot the extends keyword

here is the corrected code


class SuperClass
{
public static function connect()
{
echo "hello ".self::$user;
}
}

class ChildA extends SuperClass
{
protected static $user = 'John';
}

class ChildB extends SuperClass
{
protected static $user = 'Smith';
}

ChildA::connect();

but it gives me this error :
Fatal error: Access to undeclared static property: SuperClass::$user in /home.10/cercleso/www/testingzone/classe.static.php5 on line 7

line 7 being : echo "hello "...

RonPK

9:53 pm on Jul 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If I understand all this new PHP5 OOP stuff correctly, the whole idea of static methods in classes is that they can be called without instantiating the class. Therefore things like extensions and inheritance do not apply. The manual [php.net] says: "In fact static method calls are resolved at compile time." That would explain the error you're getting about the non-existing $user, which is declared in the child classes.

[edited by: RonPK at 9:53 pm (utc) on July 17, 2006]