Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    922
    Thanks
    302
    Thanked 3 Times in 3 Posts

    Question Calling Static Method inside non-Static Method

    Hi

    I would like to know if the following is correct way of doing?


    PHP Code:
    class Foo
    {
        static public function 
    Hello() {
            return 
    'Hello';
        }

        public function 
    World(){
            return 
    self::Hello() .' World';
        }

    Here I am calling a static method inside a non-static method. It works for sure, but just wanted to confirm if its correct way??


    Thanks
    Last edited by phantom007; 06-03-2014 at 09:05 AM.

  • #2
    Regular Coder
    Join Date
    Sep 2011
    Posts
    428
    Thanks
    18
    Thanked 26 Times in 26 Posts
    Yes this is correct.

    "Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can)." - PHP.net

    You can't call static functions in an object, you must reference the class instead. The function also cannot rely on any variables or functions within the class that are not static (meaning you cant use $this->... in the function). If you wish to call the function outside the class you can do so by replacing self with the class name (ex. Foo::Hello();).

  • #3
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    922
    Thanks
    302
    Thanked 3 Times in 3 Posts
    Cool, thanks


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •