Guest User

Untitled

a guest
Aug 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. What happens in this code block during php oop?
  2. <?php
  3. class xyz {
  4. public function foo(Request $request){
  5. //some code
  6. }
  7. }
  8.  
  9. <?php
  10. // An example class
  11. class MyClass
  12. {
  13. /**
  14. * A test function
  15. *
  16. * First parameter must be an object of type OtherClass
  17. */
  18. public function test(OtherClass $otherclass) {
  19. echo $otherclass->var;
  20. }
  21.  
  22.  
  23. /**
  24. * Another test function
  25. *
  26. * First parameter must be an array
  27. */
  28. public function test_array(array $input_array) {
  29. print_r($input_array);
  30. }
  31. }
  32.  
  33. // Another example class
  34. class OtherClass {
  35. public $var = 'Hello World';
  36. }
  37.  
  38. <?php
  39. // An instance of each class
  40. $myclass = new MyClass;
  41. $otherclass = new OtherClass;
  42.  
  43. // Fatal Error: Argument 1 must be an object of class OtherClass
  44. $myclass->test('hello');
  45.  
  46. // Fatal Error: Argument 1 must be an instance of OtherClass
  47. $foo = new stdClass;
  48. $myclass->test($foo);
  49.  
  50. // Fatal Error: Argument 1 must not be null
  51. $myclass->test(null);
  52.  
  53. // Works: Prints Hello World
  54. $myclass->test($otherclass);
  55.  
  56. // Fatal Error: Argument 1 must be an array
  57. $myclass->test_array('a string');
  58.  
  59. // Works: Prints the array
  60. $myclass->test_array(array('a', 'b', 'c'));
  61. ?>
  62.  
  63. <?php
  64. class User
  65. {
  66. private $username;
  67.  
  68. public function get_username()
  69. {
  70. return $this->username;
  71. }
  72. }
  73.  
  74. class xyz()
  75. {
  76. public function foo(User $currentUser)
  77. {
  78. $currentUser->get_username();
  79. }
  80. }
  81.  
  82. $x = new xyz();
  83.  
  84. $u = new User();
  85. $x->foo($u); // That will not produce any error because we pass an Object argument of type User
  86.  
  87. $name = "my_name";
  88. $x->foo($name); // This will produce an error because we pass a wrong type of argument
  89. ?>
  90.  
  91. $request instanceof Request == true
Add Comment
Please, Sign In to add comment