Reputation: 16092
Class a {
public function __construct($a){
$this->age = $a;
}
}
Class b extends a {
public function printInfo(){
echo 'age: ' . $this->age . "\n";
}
}
$var = new b('age');
$var->printInfo();
I understand how this code works, however is it possible to pass arguments to the constructor of the class and parent class?
My attempt below is causing an error
Class a {
public function __construct($a){
$this->age = $a;
}
}
Class b extends a {
public function __construct($name){
$this->name = $name;
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->age . "\n";
}
}
$var = new b('name', 'age');
$var->printInfo();
?>
Upvotes: 0
Views: 104
Reputation: 16948
Yes, you simply need to use the parent::__construct()
method.
Like so:
class a{
/**
* The age of the user
*
* @var integer
*/
protected $age;
function __construct($a){
$this->age = $a;
}
}
class b extends a{
/**
* The name of the user
*
* @var string
*/
protected $name;
function __construct($name,$age){
// Set the name
$this->name = $name;
// Set the age
parent::__construct($age);
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->age . "\n";
}
}
$var = new b('name','age');
$var->printInfo();
Just make sure the variables are set to public or protected!
Upvotes: 3
Reputation: 588
Here is how is should go:
<?php
class a {
private $age;
public function __construct($age){
$this->age = $age;
}
public function getAge()
{
return $this->age;
}
}
class b extends a {
private $name;
public function __construct($age, $name){
parent::__construct($age);
$this->name = $name;
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->getAge() . "\n";
}
}
$b = new b(20, "Bob");
$b->printInfo();
?>
Upvotes: 0
Reputation: 11853
Just call parent::__construct in the child. for example
class Form extends Tag
{
function __construct()
{
parent::__construct();
// Called second.
}
}
Upvotes: 0
Reputation: 3105
Yes you can pass the argument to the class as well as parent class
Class a {
public function __construct($age){
$this->age = $a;
}
}
Class b extends a {
public function __construct($name,$age){
parent::__construct($age);
$this->name = $name;
}
}
$var = new b('name', 'age');
?>
Upvotes: 0
Reputation: 11830
You can pass value to the parent constructor but the way you are doing is wrong,
$var = new b('name', 'age');
it is as if the child class accepts two parameters in its constructor but in real it has only one parameter.
You can pass parameter to parent constructor something like this
parent::__construct($var);
So change you class b to this
Class b extends a {
public function __construct($name, $age){
$this->name = $name;
parent::__construct($age);
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->age . "\n";
}
}
Upvotes: 0