Jump to content

PHP Ignoring Static Keyword?


NightCabbage

Recommended Posts

Hey everyone

 

Just got an odd problem here...

 

I've set up a class, as the example below, and it seems to be ignoring the use of the "static" keyword completely.

 

<?php
class Happy
{
    static function printBlah()
    {
        echo "Blah";
    }
    
    function printMoo()
    {
        echo "Moo";
    }
}

Happy::printBlah();
Happy::printMoo();

$pie = new Happy();
$pie->printBlah();
$pie->printMoo();
?>

 

Output:

 

BlahMooBlahMoo

 

I'd expect the output to be something like:

 

Blah[error][error]Moo

 

Any idea what's going on here?

 

I'm probably just doing something stupid (am quite tired)...

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/148044-php-ignoring-static-keyword/
Share on other sites

From http://us3.php.net/manual/en/language.oop5.static.php

 

"A member declared as static can not be accessed with an instantiated class object (though a static method can)."

 

A static method is very different from a static member.  A method is still the same method whether it is called statically or from an instance.  Members are different because they require storage space, and they must be stored either globally (static) or per-instance (non-static).

A static method is very different from a static member. A method is still the same method whether it is called statically or from an instance. Members are different because they require storage space, and they must be stored either globally (static) or per-instance (non-static).

Thanks btherl :)

 

I'm from a programming background, so I didn't expect this behaviour!

 

So there's no difference between a static and a non-static function?

(other than for readability and human reference?)

 

(how do you mark a topic as solved?)

Yep, PHP treats it as an advisory thing, not as a declaration of how you will use it.  PHP is a bit loose in its enforcement of things like this.  It enforces things when it is forced to (because it affects implementation), but lets a lot of other things go.

 

Mark, you can call any method in php without instantiating the class, but php will generate a warning if it's not declared static.

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.