In classes, most people use public function name() { } to define methods. However, I have seen several examples of them being defined without the public keyword, like function name() { }. I was confused by this because I thought you had to use public/private/protected when inside a class.
I made the same sort of thing and function was doing the exact same job as public function. 
So my question is, what is the difference between using function and public function when inside a class?
Omitting the visibility is legacy code. PHP 4 did not support public, protected and private, all methods were public.
Short: "public function" == "function" // true
See also the PHP manual:
// This is public function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); }
Similarly var $attribute; is equivalent to public $attribute. The var version also is PHP 4 legacy code.
There's no difference in PHP >=5. Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
When you don't set the visibility of a method in php, it's the same as setting it as public.
From PHP Manual:
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Declare a public constructor
    public function __construct() { }
    // Declare a public method
    public function MyPublic() { }
    // Declare a protected method
    protected function MyProtected() { }
    // Declare a private method
    private function MyPrivate() { }
    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}
                        If you define with simply function means, default it takes public scope (default) from PHP 5.
function sample { }
and
public function sample { }
are no difference between them.
private => can access the property with in the class
protected => can access the property own class and sub classes
public => can access anywhere in application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With