Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between functions and public functions in classes

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?

like image 489
James Avatar asked Feb 20 '14 16:02

James


4 Answers

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.

like image 122
TimWolla Avatar answered Oct 08 '22 00:10

TimWolla


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.

like image 44
ziollek Avatar answered Oct 07 '22 23:10

ziollek


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();
    }
}
like image 3
Guilherme Vaz Avatar answered Oct 07 '22 22:10

Guilherme Vaz


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.

like image 3
kpmDev Avatar answered Oct 07 '22 22:10

kpmDev