PHP Class, Interface, Inheritance -


i trying understand inheritance in php. have 2 classes shopproduct , cdproduct. shopproduct class have 1 method getname. cdproduct class inherit (extends) shopproduct class , have method dowork. in index.php file create 1 cdproduct object , pass method takes 1 parameter function work(shopproduct $item){...}. now, can understand can call getname method using $item parameter, , know can call dowork method using $item, can't understand how possible... hope clear... :-)

it's possible because object passed parameter happens contain dowork method. it's risky calling sort of methods (belonging inheriting class) without type-checking.

why let give cdproduct parameter when mentioned 1 shopproduct? class derived shopproduct contain attributes , methods, not affecting functionality in method body.

what can achieved through having work method can receive parameter type derived shopproduct(cdproduct, bookproduct, candyproduct) without needing separate function each type [workcd(cdproduct $item) or workbook(bookproduct $item)] same thing.

if need access derived-type specific methods , attributes can switch on object class name:

switch(get_class($item)) {      case "cdproduct":         //cdproduct object specific code here      break;      case "bookproduct":          //bookproduct object specific here      break;      //and , forth...  } 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -