Guest User

Untitled

a guest
Aug 10th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. Object model design; base class awareness of derived classes
  2. abstract class AbstractNode{
  3.  
  4. protected $_parent;
  5.  
  6. public function __construct(self $parent = null){
  7. $this->_parent = $parent;
  8. }
  9.  
  10. public function get_parent(){
  11. return $this->_parent;
  12. }
  13.  
  14. }
  15.  
  16. class NodeOne extends AbstractNode{ }
  17.  
  18. class NodeTwo extends AbstractNode{ }
  19.  
  20. // more derivatives
  21.  
  22. public function get_node_one_ancestor(){
  23. if($this->_parent instanceof NodeOne){
  24. return $this->_parent;
  25. }
  26. if(null !== $this->_parent){
  27. return $this->_parent->get_node_one_ancestor();
  28. }
  29. return null;
  30. }
  31.  
  32. <root>
  33. <foo id="1">
  34. <bar id="2"></bar>
  35. <bar id="3">
  36. <foo id="4">
  37. <bar id="5">
  38. <foo id="6">
  39. <bar id="7"></bar>
  40. </foo>
  41. </bar>
  42. <bar id="8"></bar>
  43. </foo>
  44. </bar>
  45. </foo>
  46. </root>
  47.  
  48. public function get_ancestor($type){
  49. if($this->_parent instanceof $type){
  50. return $this->_parent;
  51. }
  52. if(null !== $this->_parent){
  53. return $this->_parent->get_ancestor($type);
  54. }
  55. return null;
  56. }
Add Comment
Please, Sign In to add comment