how to access parent variable from child class - php

i have two classes one parent and the other extends , I need to use main vars in extended class.
for example
class parentClass
{
$this->value = null
function __construct()
{
echo "im parent" ;
}
}
class childClass extends parentClass
{
function sayIt()
{
var_dump($this->value);
}
}
$p = new parentClass ;
$p->value = 500 ;
$c = new childClass ;
$c->sayIt(); // this output null ! i want it to output 500 , how i can do that
thanks

that's not the way inheritance works. The childClass is not automatically connected to the parent class, it just inherits from the parentClass it just inherits all public and protected variables/methods from teh parent. It is not connected to the parent's instances.
if you wnat it to output 500 you have to assign it to the child class instance somehow:
$c = new childClass ;
$c->value = 500;
$c->sayIt()
If you need a variable shared between all classes and instances you can use a static variable.

Bad Bad Bad The code is strictly for educational purpose i would advice you to get a book on basic Principles of Object Oriented programming
Making your variable static would make it accessible via the child class
class parentClass {
public static $value = null;
function __construct() {
echo "patent called";
}
}
class childClass extends parentClass {
function sayIt() {
var_dump(self::$value);
}
}
$p = new parentClass();
parentClass::$value = 500;
$c = new childClass();
$c->sayIt();

you are confusing with class constructs and references.
$p is an instance of the parentclass.
$c is an instance of the childclass.
they don't share their data.

Related

Pass arguments to parent class constructor in PHP?

I have 2 classes where parent is inherited by child.
class parentClass
{
private $table_name='';
public function __construct($argument)
{
$this->table_name=$argument;
echo $this->table_name;
}
}
class child extends parentClass
{
private $table="student";
public function __construct()
{
parent::__construct($this->table);
}
}
There is some thing like this below that has to be used but I am unable to understand how and why.
$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);
Help me as
What should be the correct code to achieve the correct logic
and please support it with a reference to gain a better understanding.
Not a direct answer, but if I read the code correctly, you don't really want to pass a variable / value to the constructor. Instead you want to pass a fixed class property like a table name.
In that case you could use a constant in the child class and set that in the parent's constructor. The child class would not need a separate constructor if that is all you want to do.
So something like:
class parentClass
{
private $table_name;
function __construct() {
$this->table_name = static::TABLE;
echo $this->table_name;
}
}
class childClass extends parentClass
{
const TABLE = "student";
}
$obj = new childClass();

PHP: how to access the data members of super class in subclass with the same name?

I searched everywhere but did not find any solution to this question.
Following is my code where I want to access the $myvar of the super class in the subclass but I don't know how? when I use $this keyword it accesses the variable in the same class but not the one in super class. please any help will be greatly appreciated.
<?php
class First{
protected $myvar = "First Class";
}
class Second extends First{
public $myvar = "Second Class";
function __construct(){
echo $this -> myvar;// here I want to access the $myvar of super class
}
}
$obj = new Second();
?>
Note: I can achieve the same functionality in java by using the super keyword.
You may create a custom function that returns the variables from the parent class BUT keep in mind that the variables should be "private":
class First{
private $myvar = "First Class";
protected function get_variable($var_name)
{
return $this->{$var_name};
}
}
class Second extends First{
public $myvar = "Second Class";
function __construct() {
echo parent::get_variable('myvar');
}
}
$obj = new Second();
The way you try to do this will not work, as Rizier mentioned. Maybe static properties can be useful to you (depending on your needs ofcourse)
<?php
class a {
protected static $var = 'a';
}
class b extends a {
protected static $var = 'b';
public function __construct() {
echo self::$var;
echo parent::$var;
}
}
$b = new b();
You could also reconstruct a in b. You'd be able to leverage the inheritance for methods and maybe other properties, while being able to use the default value in a-constructor.
<?php
class a {
protected $var = 'a';
}
class b extends a {
protected $var = 'b';
public function __construct() {
echo $this->var;
$a = new a();
echo $a->var;
}
}
$b = new b();
The main question I think you should answer is why you want a class to inherit from another but still want to be able to change/modify stuff in the parent. That's kinda counterproductive for the whole inheritance design.
You can't you are overwritten in when creating the sub class which inherits from the parent class. So you would have to change the name for it.
You override the parent parameter with:
public $myvar = "Second Class";
Remove this line to use the inherits from parent class or change the name of the child class parameter.

Are protected attributes available to parent classes in PHP?

I know that protected attributes are available to subclasses when they are defined in a class, but are they available in parent classes? For example:
class My_Class {
// Is $name available here?
}
class My_Subclass extends My_Class {
protected $name = 'Henry';
}
Code which you write in the parent class can access that property if run in the context of a subclass. Made sense? Example:
class My_Class {
public function test() {
echo $this->name;
}
}
class My_Subclass extends My_Class {
protected $name = 'Henry';
}
$a = new My_Class;
$b = new My_Subclass;
$a->test(); // doesn't work
$b->test(); // works
Obviously (hopefully), instances of My_Class won't suddenly sprout a name property, so $a->test() won't work. Precisely because of that it's a very bad idea to make a class rely on properties which it doesn't define.
Visibility doesn't only relate to $this BTW, watch:
class My_Class {
public function test($obj) {
echo $obj->name;
}
}
class My_Subclass extends My_Class {
protected $name = 'Henry';
}
$a = new My_Class;
$a->test(new My_Subclass); // Amazeballs, it works!
A parent class has access to the property if and when it tries to access it. That doesn't mean all parent classes suddenly get a copy of that property themselves.
The parent class has no information about its subclasses, so no, $name is not available in My_Class.
Edit: As #deceze points out correctly in a comment code in My_Class can access $name, but that only works if the object was instantiated from a subclass implementing that variable. Accessing the variable in the parent class will give an Undefined Property notice.
Also I would consider that bad style and architecture, but that's my opinion ;)
Sometimes it 'can', but you really shouldn't do it
class A {
function set() {
$this->v = 'a';
}
function get() {
return $this->v;
}
}
class B extends A{
protected $v = 'b';
}
echo $b->get();//b
$b->set();
echo $b->get();//a
var_dump($b); //class B#1 (1) { protected $v => string(1) "a"}
$a = new A();
echo $a->get(); //Undefined property: A::$v
$a->set();
$a->get();//a
var_dump($a); //class A#2 (1) { public $v => string(1) "a"}
No. "protected" access modifier makes any property and method to be visible from the derived class. This is what it is used for. But parent class never knows any information about the derived class.
For more information please see this article.

Properties shared between child and parents class in php

class parents{
public $a;
function __construct(){
echo $this->a;
}
}
class child extends parents{
function __construct(){
$this->a = 1;
parent::__construct();
}
}
$new = new child();//print 1
This code above print 1,which means whenever we create an instance of a child class,and assign value to properties inherited from its parent,the property in its parent class also has been assigned.But the code below shows different:
class parents{
public $a;
function test(){
$child = new child();
echo $this->a;
}
}
class child extends parents{
function __construct(){
$this->a = 1;
}
}
$new = new parents();
$new->test();//print nothing
Where I assign value to its child class and the parent apprently didn't have the value it assigned to its child class,why?
Thanks!
In the top example, since the construct function is being called from the child class, it is treating the object being used as if it were the child object that is just using a function in the parent class as if it were it's own.
In the bottom example you have two separate objects acting independently. The parent object has it's $a and so does the child, but they are not the same $a since they are contained in separate objects. so when you print $this->a in the parent class, it is referring to the parent's instance of $a whereas if you echo $a after setting $this->a =1 in the child class it would display the child's instance of $a.
Hope this cleared some stuff up for you.
You are mixing object composition and class inheritance.
Inheritance (realized through the extends keyword) defines an is a relationship.
Composition defines a has a relationship.
To illustrate this concept we will start with inheritance.
class Person {
public $name;
public function talk(){};
public function poop(){};
}
class Parent extends Person {
public function __construct($name) {
$this->name = $name;
}
}
class Child extends Person {
public function __construct($name){
$this->name = $name;
}
}
In this example we are defining a class of things called People. From that definition we are deriving two different subtypes of People, Parent and Child. When we subtype a class then the subtype gains it's own copy of all of the properties and has access to all of the methods defined in the base type, so without defining it a Child and Parent have a name and can both talk and poop by virtue of also being a person.
For example:
$parent = new Parent("Homer");
$child = new Child("Bart");
$parent->talk();
$child->poop();
Composition is used when you want to implement a has a relation ship. Lets revise our type definition of Parent.
class Parent extends Person {
public $children = array();
public function __construct($name) {
$this->name = $name;
}
public function addChild(Child $child){
$this->children[] = $child;
}
}
What we have now allowing if for a Parent to have a child.
$parent = new Parent("Homer");
$child = new Child("Bart");
$parent->addChild($child);
// now I can access homers first child
echo $parent->children[0]->name;
When you instantiate parent, the instance of child created extends the parent class with to test() function. However, that doesn't change the value of $a.
That happens, because you have two different instances, which have nothing in common(except the the inheritance..)
The behavior you except could be generated with inner classes - which php don't support.
If you want to share an var accros every instance, you have to make it static
class parents{
public static $a;
function test(){
$child = new child();
echo self::$a;
}
}
class child extends parents{
function __construct(){
self::$a = 1;
}
}
$new = new parents();
$new->test();
which isn't probably what you want. Or you tell exactly, where you want to change your var
class parents{
public $a;
function test(){
$child = new child();
echo $child->a;
}
}
class child extends parents{
function __construct(){
$this->a = 1;
}
}
$new = new parents();
$new->test();
It's because in the first example you instantiate child
$new = new child();//print 1
and in the second you instantiate parents
$new = new parents();
The second works the same as the first using $new = new child();
If you want to access $a by instantiating child() you need to do it like this:
class parents{
public $a;
function test(){
$child = new child(); //CHANGE HERE
echo $child->a;
}
}
class child extends parents{
function __construct(){
$this->a = 1;
}
}
$new = new parents();
$new->test();

accessing a child class prop from parent

I mean something like that:
class parentClass {
public function method() {
echo $this->prop;
}
}
class childClass extends parentClass {
public $prop = 5;
}
How can I get a child prop from the parent prop?
Thanks...
Either I don't fully understand what you want or the solution is as trivial as the following code.
class parentClass {
public function method() {
echo $this->prop;
}
}
class childClass extends parentClass {
public $prop = 5;
}
$object = new childClass();
$object->method();
I mean the child class is extending the base class which means it will also inherit all the methods of its parent's class. That makes the whole process of using the parent's class method as simple as calling it from the instance of the child class.
All protected and public members of child classes are visible from within their parent class in PHP, so the example code you provided should work just fine. Quote from the php doc:
Members declared protected can be accessed only within the class
itself and by inherited and parent classes.
But the actual question is: do you really need it?
The proper OO way would be to define a self-contained parent class that expresses something. It should not need to access properties of child classes - this is a so-called code smell. If you really think that you have a case where a similar construct is necessary, you are probably looking for abstract methods, which guarantee that every child class has this property:
abstract class Animal {
public function makeNoise() {
echo $this->getNoiseString();
}
protected abstract function getNoiseString();
}
class Cat extends Animal {
protected function getNoiseString() {
return 'meow';
}
}
//parent
class parentClass {
protected $prop = null;
public function method() {
echo $this->prop;
}
}
//child
class childClass extends parentClass {
protected $prop = 5;
}
Make sure the variable is defined in the parentclass as well. So it will be accessible by the parent.

Categories