1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

php static functions

Discussion in 'Web Design & Development' started by andynic, Jan 31, 2015.

Thread Status:
Not open for further replies.
Advertisement
  1. andynic

    andynic Thread Starter

    Joined:
    May 25, 2007
    Messages:
    385
    Hi,

    I am in the process of learning to program in PHP in the object oriented model. Maybe my question also applies in general to PHP i.e. also to procedural programming.

    I can't find satisfactory info about the keyword "static" and what it actually does. The PHP manual is not much help from what I can see.

    I have read the Wikepedia article about the static keyword at (http://en.wikipedia.org/wiki/Static_(keyword)) but what is said there does not seem to apply to PHP. That article classifies the static keyword as a "storage class".

    A couple of specific questions:
    1. What does the static keyword control. Is it as Wikipedia suggests a "storage class" and if so what does that mean?

    2. If it is a "storage class", what other keyword options are there and what does each do in contrast to "static"?
    2.1 If there are other keyword options and you omit them from a declaration, which is the default?

    Any clarification would be much appreciated.

    Andynic
     
  2. colinsp

    colinsp

    Joined:
    Sep 5, 2007
    Messages:
    2,290
    First Name:
    Colin
  3. andynic

    andynic Thread Starter

    Joined:
    May 25, 2007
    Messages:
    385
    Hi Colin,
    Thanks for the reply and the links.
    Unless I'm misreading, I don't find the answers to my questions in those links.
    Andynic
     
  4. Ent

    Ent Trusted Advisor

    Joined:
    Apr 11, 2009
    Messages:
    5,467
    First Name:
    Josiah
    Static isn't a thing in procedural programming, or perhaps it's more accurate to say static is everything in procedural programming. For your purposes, it is an OOP term that means "not tied to a single object".
    If we assume that we're talking about a "car" class,
    we have regular (not static) variables such as numberPlate or position. Clearly different car objects have different number plates and (baring tragedy) different positions. That's not to say that not static means it must be unique; colour would also be a regular property of a car object because it makes conceptual sense to talk about the colour of that car.
    We also have regular (not static) methods in our car class, such as accelerate or refuel. Accelerate is something you do to that car, and in programming terms involves changing some of the variables associated with that car object.

    However, there are some things that don't make sense when talking about "that car" in particular, but instead when talking about the more general concept of "a car".
    Hence, for example, we might have a method to check whether a given person is licensed to drive. That isLicensed(person) method should probably be static because it's tied to the concept of "a car" rather than to a particular object, and checking whether someone can drive a car is the same whatever car they happen to be thinking of driving. You could even reasonably talk about whether a person is licensed to drive a car even if there are no actual car objects in your program!

    It is worth noting that because static methods are not tied to a given object, they cannot refer to methods and variables which are not static. It would not make sense, for example, for isLicensed to go checking the level of fuel in the car because different cars have different amounts of fuel. The reverse is not true; there is nothing wrong with a regular method refering to a static method or variable because a particular car can certainly do something which cars in concept can do. Hence, for example, if the car has a regular method drive(person, location) which gets that car to drive somewhere, there is nothing wrong with it checking isLicensed(person) because if the person is licensed to drive any car, they're allowed to drive this one.

    In terms of usage, it's normally frowned upon by people pushing "pure" OO and if you have a lot of static methods or variables something is probably wrong, but when it doesn't make sense even in concept for something to belong to a particular object, you want to make it static.
     
  5. andynic

    andynic Thread Starter

    Joined:
    May 25, 2007
    Messages:
    385
    Hi Ent,

    Thanks very much for the detailed reply.

    In terms of my remarks that follow, please keep in mind that as far as OO PHP is concerned, I am a newbie and am learning.

    I've written a short program to demonstrate my confusion (please see below along with its output). In spite of your explanation, what the results from my experiment tell me is that "static" is superfluous and has no impact whatsoever. With or without the "static" qualifier, if a function is "public", it can be called with or without instantiation of the class. Furthermore I can find no alternative keyword relative to "static".

    In the case of visibility, a concept which makes sense to me, is that there are 3 keywords: public, protected, and private and, in PHP, not specifying visibility defaults to "protected". (In the case of "static", if it is not specified, what does it default to?)

    What I find odd is that in PHP all public methods seem to be callable with or without instantiation of the class. I'm sure that I am missing something and perhaps you or someone else could point out my misconception.

    Code:
    <?php
    
    class talk
    {
      // Since visibility is not specified, I assume this is public.  Is that correct?
      function Hi()  {
        echo "Hi from unqualified function Hi().  Am I static or not?<br />";
      }
    
      // Since visibility is not specified, I assume this is also public.  Is that correct?
      static function staticHi() {
        echo "Hi from static function staticHi().<br />";
      }
    
      protected function protectedHi()  {
        echo "Hi from unqualified function protectedHi().  I am protected but am I static or not?<br />";
      }
    
      protected static function protectedStaticHi() {
        echo "Hi from protected static function protectedStaticHi().<br />";
      }
    }
    
    
    // No visibility specified (default is "public").
    echo "1. Calling unqualified function Hi() without instantiating class talk:<br />";
    talk::Hi();
    echo "<br /><br />";
    
    echo "2. Calling static function staticHi() without instantiating class talk:<br />";
    talk::staticHi();
    echo "<br /><br />";
    
    echo "3. Calling unqualified function Hi() after instantiating class talk:<br />";
    $talkObj1 = new talk();
    $talkObj1->Hi();
    echo "<br /><br />";
    
    echo "4. Calling static function staticHi() after instantiating class talk:<br />";
    $talkObj2 = new talk();
    $talkObj2->staticHi();
    echo "<br /><br />";
    
    
    
    // With visibility specified as "protected" -- all of these raise errors
    /*
    echo "5. Calling unqualified function protectedHi() without instantiating class talk:<br />";
    talk::protectedHi();
    echo "<br /><br />";
    Raises error: PHP Fatal error:  Call to protected method talk::protectedHi() from context '' in staticFctTest.php
    */
    
    /*
    echo "6. Calling static function protectedStaticHi() without instantiating class talk:<br />";
    talk::protectedStaticHi();
    echo "<br /><br />";
    Raises error: PHP Fatal error:  Call to protected method talk::protectedStaticHi() from context '' in staticFctTest.php
    */
    
    /*
    echo "7. Calling unqualified function protectedHi() after instantiating class talk:<br />";
    $talkObj3 = new talk();
    $talkObj3->protectedHi();
    echo "<br /><br />";
    Raises error: PHP Fatal error:  Call to protected method talk::protectedHi() from context '' in staticFctTest.php
    */
    
    /*
    echo "8. Calling static function protectedStaticHi() after instantiating class talk:<br />";
    $talkObj4 = new talk();
    $talkObj4->protectedStaticHi();
    echo "<br /><br />";
    Raises error PHP Fatal error:  Call to protected method talk::protectedStaticHi() from context '' in staticFctTest.php
    */
    ?>
    
    OUTPUT -- of the code above including case 8 but not showing 5, 6, and 7 which produce the same result as 8:
    1. Calling unqualified function Hi() without instantiating class talk:
    Hi from unqualified function Hi(). Am I static or not?


    2. Calling static function staticHi() without instantiating class talk:
    Hi from static function staticHi().


    3. Calling unqualified function Hi() after instantiating class talk:
    Hi from unqualified function Hi(). Am I static or not?


    4. Calling static function staticHi() after instantiating class talk:
    Hi from static function staticHi().


    8. Calling static function protectedStaticHi() after instantiating class talk:
    (HERE THE ERROR GETS RAISED IN THE APACE ERROR LOG)

    END OF OUTPUT.

    Thanks for your help.
    Andynic
     
  6. Ent

    Ent Trusted Advisor

    Joined:
    Apr 11, 2009
    Messages:
    5,467
    First Name:
    Josiah
    Protected is a different issue. In summary, if something in a class is protected, stuff outside the class isn't allowed to touch it. Again by analogy, you might make the internal workings of your car "protected" so that nothing can change the state of the engine except through the interface (e.g. steering wheel) you provide. That just helps guarantee that stuff works, because you only have to consider a small number of possible changes that people are allowed to make.

    Now, on to the static thing.
    If you do not have the keyword static, it isn't static.
    When I run your script, I get a warning in the first test reading "Strict standards: Non-static method talk::Hi() should not be called statically in C:\wamp\www\test\objTest.php on line 27".
    The other three tests are fine, as expected.

    It is worth noting that I just get a warning and not an error, because fundamentally none of your functions refer to anything outside themselve at all.
    Let's say instead our code looks like this:
    Code:
    class talk
    {
      private $personName; // this is a property of the talk object.
      function __construct($newName) { // and this is a constructor that sets said property.
           $this->personName = $newName;
       }
      
      // This is not a static function.
      function Hi()  {
        echo "Hi, " . $this->personName . ", from unqualified function Hi().  Am I static or not?<br />";
      }
    }
    
    Now, clearly you can't just call talk::Hi() because it doesn't have an actual object to refer to, and doesn't know what name to use.

    Instead you can instanciate this with
    Code:
    $talkObj1 = new talk("Andynic");
    $talkObj1->Hi();
    This would return "Hi, Andynic, from unqualified function Hi(). Am I static or not?"

    If you tried to write a staticHi in the same way it would fail, because static methods are not allowed to refer to variables associated with a particular instance.
     
  7. andynic

    andynic Thread Starter

    Joined:
    May 25, 2007
    Messages:
    385
    Thanks, Ent.
    That was very helpful.
    Andynic
     
  8. Sponsor

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 733,556 other people just like you!

Loading...
Similar Threads - static functions
  1. Rednecklady54
    Replies:
    7
    Views:
    620
Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/1142217

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice