R
R
Ruplex2014-12-25 20:23:45
PHP
Ruplex, 2014-12-25 20:23:45

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()); // Пытаемся получить установленное значение.

I need to get the set value (Test2) of a parent class property.
Please explain to me, a fool, what exactly am I missing and how can I solve this problem.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Stanislav, 2014-12-25
@Ruplex

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()); // Пытаемся получить установленное значение.

I
index0h, 2014-12-25
@index0h

You are confusing objects and classes, they are fundamentally different things.
What you want can be done with static properties.

K
KorsaR-ZN, 2014-12-25
@KorsaR-ZN

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

D
Dmitry Kamyannoy, 2014-12-26
@redfieldone

parent::()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question