Consider this PHP class and code snippet. What will be printed?
<?php class Test { public $a = 1; private $b = 2; protected $c = 3; public function printValues() { echo $this->a . ',' . $this->b . ',' . $this->c; } } $test = new Test(); echo $test->a . ','; // echo $test->b . ','; // Uncommenting this line causes error // echo $test->c; // Uncommenting this line causes error $test->printValues(); ?>
Remember that private and protected properties cannot be accessed directly outside the class, but public properties can.
The public property $a is accessible directly and prints '1,'. The private $b and protected $c cannot be accessed directly outside the class, so those lines are commented out. The printValues() method inside the class can access all three properties and prints '1,2,3'. So the full output is '1,1,2,3'.
What error will this PHP code produce?
<?php class Sample { private $secret = 'hidden'; } $obj = new Sample(); echo $obj->secret; ?>
Private properties cannot be accessed from outside the class.
Trying to access a private property directly from outside the class causes a fatal error in PHP. The error message says you cannot access the private property.
Look at this PHP code. Why does it cause an error?
<?php class ParentClass { protected $value = 10; } class ChildClass extends ParentClass { } $obj = new ChildClass(); echo $obj->value; ?>
Think about where protected properties can be accessed from.
Protected properties can be accessed inside the class where they are declared and in child classes, but not from outside objects. Accessing $obj->value from outside causes an error.
Choose the correct PHP code snippet that declares a private property $data and a public method getData() that returns it.
Remember to use function keyword and $this-> to access properties inside methods.
Option D correctly declares a private property $data and a public method getData() that returns $this->data. Option D misses public and uses $data without $this->. Option D swaps visibility and method access. Option D misses function keyword.
Given these classes, how many properties can the showProperties() method access?
<?php class Base { public $pub = 1; private $priv = 2; protected $prot = 3; } class Derived extends Base { public function showProperties() { $vars = get_object_vars($this); $count = 0; if (isset($vars['pub'])) $count++; if (isset($vars['priv'])) $count++; if (isset($vars['prot'])) $count++; return $count; } } $obj = new Derived(); echo $obj->showProperties(); ?>
Think about which properties are accessible inside a child class method.
The child class method can access public and protected properties from the parent class, but not private ones. So it counts $pub and $prot, but not $priv. The count is 2.