-3

Consider the following example. class b is extending class a.

1) When class b extends class a, will it overwrite property a value?

2) When class b extends class a, will it overwrite method say?

class a  {
public $a = 5;
function say() {
echo "Hi";
}
}

class b extends a {
public $a = 6;
function say() {
echo "Hi";
}
}
vivek2015
  • 1
  • 2
  • You're missing $ before variable names – Waldson Patricio Jan 08 '15 at 13:53
  • 1
    Why not just test this? – Digital Chris Jan 08 '15 at 13:53
  • but i can access class a propertry and method using parent in class b? how? if class b overwritten class a propertry and method? – vivek2015 Jan 08 '15 at 13:58
  • 1
    @vivek2015 Class B does not `overwrite` the method, it `overrides` the method. The actual method in class A will still exist for other instances/children to use. – DarkBee Jan 08 '15 at 14:03
  • methods can be accessed by parent::method() (in your example: parent::say() ). But usually it is not necessary to do so (see here for reasons: http://stackoverflow.com/questions/11237511/multiple-ways-of-calling-parent-method-in-php). overriden properties can not be accessed directly, you would have to use the Reflection class. This is usually not necessary in production code, either. I suspect you confuse "class", which is kind of a template, with "object", which is a concrete instance of a class – cypherabe Jan 08 '15 at 14:32

3 Answers3

1

Yes, and Yes.

After extending a class you are able to change the default value.

See PHP: Visibility for more info.

  • but i can access class a propertry and method using parent in class b? how? if class b overwritten class a propertry and method? – vivek2015 Jan 08 '15 at 13:57
0

Yes to both. In the property case it will override the default value of it.

Waldson Patricio
  • 1,489
  • 13
  • 17
0

Yes to everything.

Object oriented programming has inheritance and if the child redeclares/redefines methods or properties the parent ones will be changed. Child classes are usually used to provide more specific functionality whereas parent classes are used for general functionality.

If you wish to keep the parent ones the following would work.

class A {
    public $a = 5;
    function say() {
        echo 'Hi';
    }
}

class C extends A {
    /* specific functionality here */
}

The pertinent and official documentation of this is here: http://php.net/manual/en/language.oop5.inheritance.php

Robert
  • 10,126
  • 19
  • 78
  • 130