在PHP中引用容器对象的方法?

前端之家收集整理的这篇文章主要介绍了在PHP中引用容器对象的方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP中给出以下内容
  1. <?PHP
  2. class foo {
  3. public $bar;
  4. function __construct() {
  5. "Foo Exists!";
  6. }
  7.  
  8. function magic_bullet($id) {
  9. switch($id) {
  10. case 1:
  11. echo "There is no spoon! ";
  12. case 2:
  13. echo "Or is there... ";
  14. break;
  15. }
  16. }
  17. }
  18.  
  19. class bar {
  20. function __construct() {
  21. echo "Bar exists";
  22. }
  23. function target($id) {
  24. echo "I want a magic bullet for this ID!";
  25. }
  26. }
  27.  
  28. $test = new foo();
  29. $test->bar = new bar();
  30. $test->bar->target(42);

我想知道’bar’类是否可以调用’foo’类的’magic bullet’方法. ‘bar’实例包含在’foo’实例中,但与它没有父/子关系.实际上,我有很多不同的“条形”类,“foo”在一个数组中,每个类都有一些与$id不同的东西,然后想要将它传递给“magic_bullet”函数以获得最终结果,因此禁止结构更改类关系,是否可以访问“容器”实例的方法

您必须修改代码才能提供关系.在OOP中,我们称之为 aggregation.

假设PHP 4,以及“一系列条形图”的想法

  1. <?PHP
  2.  
  3. class foo {
  4. var $bars = array();
  5. function __construct() {
  6. "Foo Exists!";
  7. }
  8.  
  9. function magic_bullet($id) {
  10. switch($id) {
  11. case 1:
  12. echo "There is no spoon! ";
  13. case 2:
  14. echo "Or is there... ";
  15. break;
  16. }
  17. }
  18.  
  19. function addBar( &$bar )
  20. {
  21. $bar->setFoo( $this );
  22. $this->bars[] = &$bar;
  23. }
  24. }
  25.  
  26. class bar {
  27. var $foo;
  28. function __construct() {
  29. echo "Bar exists";
  30. }
  31.  
  32. function target($id){
  33. if ( isset( $this->foo ) )
  34. {
  35. echo $this->foo->magic_bullet( $id );
  36. } else {
  37. trigger_error( 'There is no foo!',E_USER_ERROR );
  38. }
  39. }
  40. function setFoo( &$foo )
  41. {
  42. $this->foo = &$foo;
  43. }
  44. }
  45.  
  46. $test = new foo();
  47. $bar1 = new bar();
  48. $bar2 = new bar();
  49.  
  50. $test->addBar( $bar1 );
  51. $test->addBar( $bar2 );
  52.  
  53. $bar1->target( 1 );
  54. $bar1->target( 2 );

猜你在找的PHP相关文章