Friday 1 December 2017

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

itemprop="text">

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



Examples:



//
Public
public $variable;

public function doSomething()
{
// ...
}

// Private
private
$variable;
private function doSomething() {
//
...
}


// Protected
protected
$variable;
protected function doSomething() {
//
...
}

class="post-text" itemprop="text">
class="normal">Answer



You
use:





  • public
    scope to make that property/method available from anywhere, other classes and instances
    of the
    object.


  • private
    scope when you want your property/method to be visible in its own class
    only.


  • protected
    scope when you want to make your property/method visible in all classes that extend
    current class including the parent
    class.




More:
(For comprehensive information)





No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...