code_junkie

Implications of Instantiating Objects with Dynamic Variables in PHP

Nov 10th, 2011
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. <?php
  2. $class_name = 'SomeClassName';
  3. $object = new $class_name;
  4. ?>
  5.  
  6. $classname = 'SomeClassName';
  7. for ($x = 0; $x < 100000; $x++){
  8. $object = new $classname;
  9. }
  10.  
  11. <?php
  12.  
  13. class Test {
  14. function __construct($x) {
  15. echo $x;
  16. }
  17. }
  18.  
  19. $class = 'Test';
  20. $object = new $class('test'); // echoes "test"
  21.  
  22. ?>
  23.  
  24. <?php
  25.  
  26. $class = "Test";
  27. $args = array('a', 'b');
  28. $ref = new ReflectionClass($class);
  29. $instance = $ref->newInstanceArgs($args);
  30.  
  31. ?>
  32.  
  33. <?php
  34. $className = 'ClassName';
  35.  
  36. $className::someStaticMethod(); //doesn't work
  37. ?>
  38.  
  39. class Test {
  40. function testExt() {
  41. print 'hello from testExt :P';
  42. }
  43. function test2Ext()
  44. {
  45. print 'hi from test2Ext :)';
  46. }
  47. }
  48.  
  49.  
  50. $class = 'Test';
  51. $method_1 = "testExt";
  52. $method_2 = "test2Ext";
  53. $object = new $class(); // echoes "test"
  54. $object->{$method_2}(); // will print 'hi from test2Ext :)'
  55. $object->{$method_1}(); // will print 'hello from testExt :P';
Add Comment
Please, Sign In to add comment