Attribute inheritance

0

How would it be possible to access the $ foo attribute in the following inheritance example? I thought that by inheritance you could 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();
    
asked by Adrian 12.05.2017 в 14:40
source

2 answers

0

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 daughters 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();
    
answered by 12.05.2017 в 15:14
-1

You must call $ foo in the correct context.

 echo $this->foo

Also, you have to add the scope to the variable $ foo

protected $foo= 5;

    
answered by 12.05.2017 в 14:49