Public

Public variables and functions are accessible from anywhere in your script, which makes this modifier the easiest to use. In PHP 4, all object variables were declared with "var" and were essentially public, but using this terminology is deprecated and may generate compiler warnings. Take a look at this following code:

<?php
    class dog {
        public $Name;

        public function bark() {
            print "Woof!\n";
        }
    }

    class poodle extends dog {
        public function bark() {
            print "Yip!\n";
        }
    }

    $poppy = new poodle;
    $poppy->Name = "Poppy";
    print $poppy->Name;
?>

If you try that code out, you will see it works in precisely the same way as before - the public keyword does not make any difference. The reason behind is that, by default, all class functions are public, because before PHP 5 there was no way to make them anything else.

While the public keyword is not needed, I recommend you use it anyway - it is a good way to remind people who read your code that a given function is indeed public, and also it is possible that class functions without an access modifier may be deprecated in the future.

When you use public for variables, it is needed - you always need to specify an access modifier for variables, because otherwise there'd be no way to define what variables a class has. Previous versions of PHP used the "var" keyword to declare class variables, again because it had no concept of access modifiers - you should avoid this, and be more specific with public or one of the other keywords.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Private >>

Previous chapter: Access control modifiers

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.