PHP: Accessing protected var from child class - php

I'm learning PHP and I'm stuck i the following code:
<?php
class dogtag {
protected $Words;
}
class dog {
protected $Name;
protected $DogTag;
protected function bark() {
print "Woof!\n";
}
}
class poodle extends dog {
public function bark() {
print "Yip!\n";
}
}
$poppy = new poodle;
$poppy->Name = "Poppy";
$poppy->DogTag = new dogtag;
$poppy->DogTag->Words = "My name is
Poppy. If you find me, please call 555-1234";
var_dump($poppy);
?>
This is what I got:
PHP Fatal error: Uncaught Error: Cannot access protected property poodle::$Name
This looks strange to me as I should access protected vars and functions from child classes.
Could please someone explain where I'm wrong?
Many thanks.

Protected variables can indeed be accessed from the child class. However you aren't accessing your variable from inside the child class.
If you make the variables public you can access them from outside the class.
Documentation: http://php.net/manual/en/language.oop5.visibility.php
Example:
Class Dog {
private $privateProperty = "private"; //I can only be access from inside the Dog class
protected $protectedProperty = "protected"; //I can be accessed from inside the dog class and all child classes
public $publicProperty = "public"; //I can be accessed from everywhere.
}
Class Poodle extends Dog {
public function getProtectedProperty(){
return $this->protectedProperty; //This is ok because it's inside the Poodle (child class);
}
}
$poodle = new Poodle;
echo $poodle->publicProperty; //This is ok because it's public
echo $poodle->getProtectedProperty(); //This is ok because it calls a public method.

You can't access the property 'Words', you need to make it public

you could add magic methods to your class - that would allow you to access and manipulate the private properties from outside the class.
class foo{
private $bah;
public function __construct(){
$this->bah='hello world';
}
public function __get( $name ){
return $this->$name;
}
public function __set( $name,$value ){
$this->$name=$value;
}
public function __isset( $name ){
return isset( $this->$name );
}
public function __unset( $name ){
unset( $this->$name );
}
}
$foo=new foo;
echo $foo->bah;
$foo->bah='banana';
echo $foo->bah;

Related

Use of magic __set() function in base class

I have tried in yii frame work adding set function in CController and try to add property in controller's object but it gives error
Can i user base class's __set function to set property of a instance.
Class Base {
public function __set() {
$this->$name = $value;
}
}
Class SubClass1 extends Base{
}
Class SubClass2 extends Base {
}
I create instance of SubClass1 or SubClass2 and i want to add property dynamically. Is it possible.
yes you can unless the property is private
Yes you can place your magic function your your class structure. Magic functions normally calls even if you are not defining in class file.
So, if you not create __set() in your class file, it won't affect much. But, if you want to do some extra things while setting under object then it will be helpful.
Also, __set() function need two parameter, $name and $value. Please refer following url,
__set() magic function
Regards
You can indeed, the following will demonstrate:
<?php
class Foo
{
private $vars = array();
public function __set($name, $value)
{
echo "Setting $name: $value<br />";
$this->vars[$name] = $value;
}
public function __get($name)
{
echo "Getting $name<br />";
return isset($this->vars[$name]) ? $this->vars[$name] : null;
}
}
class Bar extends Foo {}
$bar = new Bar();
$bar->baz = 'baz';
echo $bar->baz;
Which will output:
Setting baz: baz
Getting baz
baz
class Base {
protected $data;
public function __construct() {
$this->someMethodBaseClass();
}
protected function someMethodBaseClass() {
$this->data = 123456;
}
}
class subclass1 extends Base{
public function __construct() {
parent::__construct();
}
public function getData() {
return $this->data;
}
}

PHP late static binding doesn't work correctly

While coding and using late static binding in PHP I found some strange behaviour. A child object created with static() in its parent class can access the private methods of its parent.
Here's an example:
class Attachment
{
public static function createFromFile($file)
{
$attachment = new static();
echo get_class($attachment) . PHP_EOL;
$attachment->loadFromFile($file);
}
private function loadFromFile($file)
{
echo 'attachment';
}
}
class PictureAttachment extends Attachment
{
//...
}
PictureAttachment::createFromFile('example.txt');
Output:
PictureAttachment
attachment
Is this a correct behaviour?
Yes, this is correct. The class that is calling the private method is the same that is declaring it. It doesn't matter that it may or may not instantiate a child class. You just can't have any code in the child class calling the private method of the parent.
In other words:
class Foo {
protected function bar() {
$this->baz();
}
private function baz() { }
}
class Bar extends Foo {
protected function bar() {
parent::bar(); // <-- works
parent::baz(); // <-- doesn't work
}
}

Inheriting instance in PHP

I try to call getTest() function inside Child class.
First I initialize instance of Ext class so I assume main property $ext should now contain it. But Child class does not inherit it and obtained error message is:
Call to a member function getTest() on a non-object
Where is the issue?
<?php
$A = new Main;
class Main
{
protected $ext = null;
function __construct()
{
$this->ext= new Ext();
new Child;
}
}
class Child extends Main
{
function __construct()
{
echo $this->ext->getTest();
}
}
class Ext extends Main
{
public function getTest()
{
return "cool";
}
}
?>
I know that to solve it other way I can use:
class Child
{
private $Main;
function __construct( &$Main ) { ... }
}
but I would like to understand why that does not work..
At the moment on construct the object the atribute don't have a value yet.
You need call to the parent constructor before use the attribute
function __construct()
{
parent::__construct();
echo $this->ext->getTest();
}

PHP Accessing Parent Class Variable

class A {
private $aa;
protected $bb = 'parent bb';
function __construct($arg) {
//do something..
}
private function parentmethod($arg2) {
//do something..
}
}
class B extends A {
function __construct($arg) {
parent::__construct($arg);
}
function childfunction() {
echo parent::$bb; //Fatal error: Undefined class constant 'bb'
}
}
$test = new B($some);
$test->childfunction();
Question:
How do I display parent variable in child?
expected result will echo 'parent bb'
echo $this->bb;
The variable is inherited and is not private, so it is a part of the current object.
Here is additional information in response to your request for more information about using parent:::
Use parent:: when you want add extra functionality to a method from the parent class. For example, imagine an Airplane class:
class Airplane {
private $pilot;
public function __construct( $pilot ) {
$this->pilot = $pilot;
}
}
Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:
class Bomber extends Airplane {
private $navigator;
public function __construct( $pilot, $navigator ) {
$this->navigator = $navigator;
parent::__construct( $pilot ); // Assigns $pilot to $this->pilot
}
}
In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.
Just echo it since it's inherited
echo $this->bb;
With parent::$bb; you try to retrieve the static constant defined with the value of $bb.
Instead, do:
echo $this->bb;
Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.
class A {
private $aa;
protected $bb = 'parent bb';
function __construct($arg) {
//do something..
}
private function parentmethod($arg2) {
//do something..
}
}
class B extends A {
function __construct($arg) {
parent::__construct($arg);
}
function childfunction() {
echo parent::$this->bb; //works by M
}
}
$test = new B($some);
$test->childfunction();`
$bb has now become the member of class B after extending class A.
So you access $bb like it's an attribute of class B.
class A {
private $aa;
protected $bb = 'parent bb';
function __construct($arg) {
//do something..
}
private function parentmethod($arg2) {
//do something..
}
}
class B extends A {
function __construct($arg) {
parent::__construct($arg);
}
function childfunction() {
echo $this->bb;
}
}
$test = new B($some);
$test->childfunction();
all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net
The visibility of a property or method
can be defined by prefixing the
declaration with the keywords public,
protected or private. Class members
declared public can be accessed
everywhere. Members declared protected
can be accessed only within the class
itself and by inherited and parent
classes. Members declared as private
may only be accessed by the class that
defines the member.
PHP Accessing Parent Class Protected Variable & Methods
class A {
protected $bb = 'parent bb';
protected function sayHello(){
echo 'Say Hello';
}
}
class B extends A {
public function childfunction() {
echo $this->bb.'<br>';
echo $this->sayHello();
}
}
$test = new B();
$test->childfunction();
Through parent class contructor you can pass data to parent class from child class. Have a look below example for better understanding
<?php
class Student
{
public $name;
function __construct($name){
$this->name = $name;
}
}
class Test extends Student
{
public $age;
function __construct($name,$age){
$this->age = $age;
parent::__construct($name);
}
}
$obj = new Test("sajib khan" ,21);
echo $obj->name;
echo $obj->age;
?>
class A {
private $points = 100;
public function getPoints() {
return $this->points;
}
}
class B extends A {
protected $points = 70;
public function getPoints() {
return parent::getPoints();
}
}
$element = new B();
echo $element->getPoints();
change the visibility private or protected for test

Edit protected member in php

I have code similar to the following:
class ModuleRaceRegistration extends Module
{
protected $strTemplate = "template";
protected function compile()
{
// this doesn't work
$this->strTemplate = "template2";
}
}
From within the compile function I need to change the $strTemplate member. How can I do this?
Is an error being returned? Also, this might not be the case but compile is a protected method so you can only call it from within the class. If you are trying to call it from outside of the class, then it would need to be public.
Let me try
Example from manual
<?php
abstract class Base {
abstract protected function _test();
}
class Bar extends Base {
protected function _test() { }
public function TestFoo() {
$c = new Foo();
$c->_test();
}
}
class Foo extends Base {
protected function _test() {
echo 'Foo';
}
}
$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>

Categories