How to use class private methods in PHP

1 Answer

0 votes
class Test 
{
    public $pr = "Class property from class Test";
    
    public function __construct()
    {
        echo 'Constructor activated from class Test <br />';
    }
      
    public function __destruct()
    {
        echo '<br /> Destructor activated from class Test <br />';
    }
    
    public function setProperty($val)
    {
        $this->pr = $val;
    }
    
    private function getProperty()
    {
        return $this->pr;
    }
    private function f()
    {
        echo "Method f() from class " . __CLASS__ . "<br />";
    }
}
  
class MyNewClass extends Test
{
    public function __construct()
    {
        parent::__construct(); 
        echo 'Constructor activated from class MyNewClass <br />';
    }
    public function runProtectedMethod()
    {
        return $this->getProperty();
    }
}
 
   
$obj1 = new MyNewClass;

$obj1->setProperty("some value");
// private methos accessible only from 
// within the class that defines it: class Test 
echo $obj1->runProtectedMethod(); 



/*
run:

Constructor activated from class Test 
Constructor activated from class MyNewClass 

Fatal error: Call to private method Test::getProperty() from context 'MyNewClass' 
in C:\xampp\htdocs\he.seek4info.com\test.php on line 46

*/

 



answered Nov 4, 2015 by avibootz

Related questions

2 answers 282 views
2 answers 322 views
322 views asked Nov 4, 2015 by avibootz
3 answers 355 views
355 views asked Nov 3, 2015 by avibootz
2 answers 239 views
239 views asked Oct 4, 2017 by avibootz
1 answer 347 views
2 answers 909 views
...