Member Avatar for LastMitch

Hi

I'm having issue of understand how to echo a variable when the class is extended. I have 2 files.

This is my index.php file:

<!DOCTYPE html> 
<html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OOP Example</title>
<?php include("class.php"); ?>
</head>
<body>
<?php 

$mitch = new person("Mitch Last");

echo "Mitch's full name: " . $mitch->get_name();"</br>";

$last = new coworker("Last Mitch");

echo "</br>Last's full name: " . $last->get_name();"</br>";

$slim = new coworker("Slim Jim");

echo "</br>Slim's full name: " . $slim->get_name();"</br>";

?>
</body>
</html>

This is my class.php file:

<?php 

class person {

// To defined adding class properties are optional
var $name;  

function __construct($new_person) {

$this->name = $new_person;

}

public function get_name() {

return $this->name;

}

//protected methods and properties restrict access to those elements.
protected function set_name($new_name) {

if (name != "Slim Jim") {
$this->name = strtoupper($new_name);
}
}

} 

// 'extends' is the keyword that enables inheritance
class coworker extends person {

protected function set_name($new_name) {

if ($new_name == "Mitch thinks") {
$this->name = $new_name;
}
else if($new_name == "Last thoughts") {
parent::set_name($new_name);
}

}

function __construct($coworker_name) {

$this->set_name($coworker_name);
}
}

?>

The issue is on my index.php file.

<?php 

$mitch = new person("Mitch Last");

echo "Mitch's full name: " . $mitch->get_name();"</br>";

$last = new coworker("Last Mitch");

echo "</br>Last's full name: " . $last->get_name();"</br>";

$slim = new coworker("Slim Jim");

echo "</br>Slim's full name: " . $slim->get_name();"</br>";

?>

Right now when I echo it out, it looks like this:

Mitch's full name: Mitch Last
Last's full name: 
Slim's full name: 

When I change new coworker() to new person() then it echo out like this:

Mitch's full name: Mitch Last
Last's full name: Last Mitch
Slim's full name: Slim Jim 

I'm confused on why new coworker() is not echoing it. I'm still new to OOP.

Any Suggestions and explanation will help. I appreciate it. Thanks!

PrimePackster commented: To Rectify what some retard did to LastMitch +0

Because you have defined a constructor for the child class the parent constructor is not implicitly called. When you define a constructor you must construct the parent to make the functions available to it:

function __construct($coworker_name) 
{
  parent::__construct();
  $this->set_name($coworker_name);
}
Member Avatar for LastMitch

@GliderPilot

Thanks for the reply and explanation and example. I will test it out now.

When you define a constructor you must construct the parent to make the functions available to it

Not entirely true. Calling the parent constructor only causes the parent's code to be executed, which assigns the passed name to the property. The functions are available anyway. The right way to invoke the parent constructor is:

function __construct($coworker_name) 
{
    parent::__construct($coworker_name);
}
Member Avatar for LastMitch

@GliderPilot

When I ran the code. I got this error:

Warning: Missing argument 1 for person::__construct() on line 8

function __construct($new_person) {

Notice: Undefined variable: new_person on line 10

$this->name = $new_person;

The result is this:

Mitch's full name: Mitch Last
Last's full name:
Slim's full name: 

Any explanation why?

I change it a bit:

function __construct($coworker_name)
{
parent::__construct();
$this->name = $coworker_name;
}

it echo both $coworker_name & $new_person

but I still get the same 2 errors.

Member Avatar for LastMitch

@pritaeas

Thanks for the reply and explanation and example. I will test out now.

Your parent class constructor requires a variable be passed to it. You need to pass the co-worker's name. parent::__construct($coworker_name);

Member Avatar for diafol

Will your person class ever be instantiated? I know you did in the example, but just curious. i.e. are you planning on making it an abstract class?

Member Avatar for LastMitch

@pritaeas

It work! Thanks!

Let me know if you need an additional explanation.

I'm bit confused I thought that I establish a parent in here:

function __construct($new_person){}

But in order to echo out $coworker_name I need to reestablish a parent in here too:

function __construct($coworker_name){}

I thought that there's only one parent in a _construct() function? But I can create 2?

Member Avatar for LastMitch

@GliderPilot

Your parent class constructor requires a variable be passed to it. You need to pass the co-worker's name. parent::__construct($coworker_name);

Yes, pritaeas explain that I can invoke it.

@diafol

Thanks for the reply & explanation.

Will your person class ever be instantiated?

I'm just practicing on an example. I don't know. I'm not that far ahead yet.

I know you did in the example, but just curious. i.e. are you planning on making it an abstract class?

No, I'm still learn regular class. I'm not that far ahead yet either.

If your child class doesn't have a constructor PHP will automatically try to execute the Parent's constructor. If you define a constructor in the child class, than you need to tell PHP to also construct the parent. There is some good info here if you're interested: http://php.net/manual/en/language.oop5.decon.php

I think you are mixing up things. Both classes have a constructor, which is called with a name parameter. The parent class stores that value in a property. In the descendant class' constructor, you did not set that property initially. By calling the parent's constructor you execute that code, thus setting the property. Instead of calling parent::... you could've copied $this->name = ...; which would have done exactly the same in your case.

Sidenote: do not use var. Use public, protected or private instead.

commented: Thanks for the explanation! +7

@lastMitch,

Here is an extremely simple example of inheritance where both the parent and the child has its own constructor.

Looking at the code, the parent does not even know that the child class exist. Only the child knows that the parent class exist.., and yes we don't have to let the parent knows whatever methods is being use by the child.

<?php

class Person{
        ## please pardon my shorthand approach. Normally, variable below are itemized for clarification.
        private $name,$lastName,$age;

        ## in older version of php, var was used instead and the constructor is not included. 
        ## However the first method should be named after the class name as in function Person().

        // var $name,$lastName,$age;
        //public function Person(){  return $name; }


        ## this is the constructor for the class Person 
        public function __construct($name,$lastName,$age){
            $this->name = $name;
            $this->lastName = $lastName;
            $this->age = $age;

        }

        public function get_name(){

        return $this->name;
        }

        public function get_info(){

            ## simple example of using another method of a class within another method within class ??????? :)
            return array($this->name,$this->lastName,self::get_age() );

        }

        public function get_age(){

        return $this->age;

        }
}

## extending the class Person above, child class can inherit all the properties of a parent class

class Info extends Person{

        ## this child class will inherit all the properties of the parent class.
        ## we can create a consructor here for this child class, and at the same time, must invoke the parent's constructor.

        public function __construct($name,$lastName,$age,$job,$hobby,$salary){

                    ## envokes the parent constructor
                    parent::__construct($name,$lastName,$age);

                    ## we only define things that are not in the parent class
                    $this->job = $job;
                    $this->hobby = $hobby;
                    $this->salary = $salary;
            }

        public function get_basic_info(){
        ## if I need to use the same method from the parent class, I can do it just like this
        $infoUser = parent::get_info();

        ## We can re-assign, repurpose, or just simply return output of the parent method get_info() in our child class.
        ## method from the parent class can be passed-on to the child class, as shown by my simple example below.
        return array($infoUser[0],$infoUser[1],parent::get_age());

        }

        public function get_bio(){

        return array($this->job,$this->hobby,$this->salary);



        }
}

## and instance of a parent class
$thisPerson = new Person('PoorBoy','North','20');
$info = $thisPerson->get_info();

## parent class items
echo 'Name: '. $info[0];
echo '<br/>Last Name : '. $info[1];
echo '<br/> Age: '. $info[2];

## instance of the child class, just like the way we would do it on the parent class
$thisChild = new Info('PoorBoy','North','20','busboy','walking','100');
$childInfo = $thisChild->get_basic_info();
$myBio = $thisChild->get_bio();

## child class items below
echo '<br/><h4>Below is the output from the child classs</h4>';
echo 'Name from Child Class: '.$childInfo[0];
echo '<br/> Last Name from Child Class: '.$childInfo[1];
echo '<br/>Age from Child Class: '.$childInfo[2];

echo '<br/><h4>Bio</h4>';
echo 'Position from the child class: '. $myBio[0];
echo '<br/> Hobby from the child class: '. $myBio[1];
echo '<br/> Salary from the child class: '. $myBio[2];
Member Avatar for LastMitch

@veedeoo

Thanks for the reply & example. The quesiton is solved. But I will test out the example that your provide.

Member Avatar for LastMitch

@pritaeas

I want to Thanks for taking your time to explain the solution & providing an example.

Thanks for being patience and helping me out with this issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.