Answer the question
In order to leave comments, you need to log in
How to inherit the value of a class property that has been set in an object (PHP language)?
Due to my inexperience and perhaps even stupidity, I can not find a solution to this problem.
The problem is that after creating an object of the class and subsequently working with it, I need to inherit those property values that were set outside the class (in the object). But when referring to a child class that inherits properties and methods, I cannot inherit the changed property of the parent class.
In general, here is a sample code:
class test {
protected $name = 'Test';
function setName($arg){
$this->name = $arg;
}
}
class test2 extends test {
function getName(){
return $this->name;
}
}
$obj = new test;
$obj->setName('Test2'); // Устанавливаем значение;
$obj = new test2;
exit($obj->getName()); // Пытаемся получить установленное значение.
Answer the question
In order to leave comments, you need to log in
Create a constructor and pass or use static.
<?php
class test {
protected $name = 'Test';
function setName($arg){
$this->name = $arg;
}
function getName(){
return $this->name;
}
}
class test2 extends test {
public function __construct($name == null){
if($name !== null) $this->name = $name;
}
function getName(){
return $this->name;
}
}
$obj = new test();
$obj->setName('Test2'); // Устанавливаем значение;
$obj = new test2($obj->getName());
exit($obj->getName()); // Пытаемся получить установленное значение.
You are confusing objects and classes, they are fundamentally different things.
What you want can be done with static properties.
No way ... Roughly speaking, inheritance is decided even before the execution of your when, so there is no way you can not inherit the properties of the object defined at the stage of code execution
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question