Public, Private and Protected

PHP 5 supports public, private and protected properties.

<?php

class foo {

    public $foo=1; // everyone can access
    private $bar=2; // can only be accessed by the class internally
    protected $baz=3; // can be accessed by the class internally & any extending classes

    function p1() { echo $this->foo . $this->bar . $this->baz; }

}

class foo_ex extends foo {

    function p2() { echo $this->foo . $this->bar . $this->baz; }

}

$a = new foo();

echo $a->p1(); // will print 123

$b = new foo_ex();

echo $b->p2(); // will print 13 + notice about unknown property foo_ex::$bar 

// accessing private/protected properties directly will result is a E_ERROR (fatal error)

echo $a->foo . $a->bar . $a->baz;
?>

Object methods can also be designated as public, private and protected. Methods without specific designation are assumed to be public.

<?php

class foo {
    public function p() {} // everyone can use
    private function p2() {} // only class foo may use internally
    protected function p3() {} // only class foo and it's extender can use
}

class foo_ex extends foo { 
    function foo_ex() { 
        $this->p2(); 
    } 
}

$a = new foo();
$a->p3(); // fatal error

$b = new foo_ex(); // will fail with fatal error

?>

Loading ...

Related Results :

  1. Public, Private and Protected
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author