What is the difference between public, private, and protected?

后端 未结 17 1563
抹茶落季
抹茶落季 2020-11-21 07:54

When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?<

17条回答
  •  孤街浪徒
    2020-11-21 08:24

    ⚡️ Here is an easy way to remember the scope of public, protected and private.

    PUBLIC:

    • public scope: A public variable/function is available to both objects and other classes.

    PROTECTED:

    • protected scope: A protected variable/function is available to all the classes that extend the current class.
    • No! Objects cannot access this scope

    PRIVATE:

    • private scope: A private variable/function is only visible in the current class where it is being defined.
    • No! Class that extend the current class cannot access this scope.
    • No! Objects cannot access this scope.

    Read the Visibility of a method or variable on PHP Manual.

提交回复
热议问题