0 votes

Attribute inheritance

How would it be possible to access the $foo attribute in the following inheritance example? I thought that through inheritance it was possible to access properties and methods of the parent class but in this example I get an error.

<?php
    class ClasePadre {
        $foo= 5;
    }

    class ClaseHija extends ClasePadre {

        public function miFuncion(){

          echo $foo;  
        }
    }

    $nueva=new ClaseHija();
    $nueva->miFuncion();

0voto

JackNavaRow Points 4207

When you declare a variable or method in a class it must indicate the visibility of the variables or method; and to see it in the child class you have to use the $this

class ClasePadre {
        protected $foo = 5;
        }
    class ClaseHija extends ClasePadre {

            public function miFuncion(){

              echo $this->foo;  
            }
        }

    $nueva=new ClaseHija();
    $nueva->miFuncion();

-1voto

LordSuricato Points 1

You must call $foo in the correct context.

 echo $this->foo

In addition, you have to add the scope to the variable $foo

protected $foo= 5;

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X