0

Morning! Suppose I wanted to be able to rewrite 'require' to do some pre/post processing to the required files, so that the below would be true:

<?php 

  registerMagicalMysteryRequireOverwrite(); 

  $xml = require './xml.xml'; 
  $dir = require './';
  $db  = require './db.sqlite';

  $isXML = $xml instanceof SimpleXML;
  $isDir = $dir instanceof RecursiveDirectoryIterator;
  $isDB  = $db instanceof SQLite3;

  $magicWorked = $isXML && $isDir && $isDB;

This could, among other things, simplify my code (like above), allow me to better sandbox other people's code (by only injecting the scope I choose into the require), let me inject random other language's code as long as a parser for them exists, etc. It would potentially be super useful. If it was a thing that existed, tho.

Can I do this? How can I do this? Thanks!

Carlos Vergara
  • 657
  • 6
  • 19
  • You can't overload/overwrite the built in functions. – Jonathan Kuhn Jun 29 '17 at 16:47
  • _"Can I do this?"_ No. PHP does not allow overloading of built-ins. `require` executes PHP source, you don't want to use it for things that aren't PHP, as you'll be opening yourself up for PHP injection vulnerabilities. – Alex Howansky Jun 29 '17 at 16:48
  • @AlexHowansky You could include/require any file whether the server is setup to handle that file as php and it will run any code inside. include/require doesn't offer any protection from including non php files as php. – Jonathan Kuhn Jun 29 '17 at 16:50
  • No, though if you're programming OOP and using an autoloader, you could modify the autoloader to handle pre/post processing; but it looks as though you're using require to include any filetype – Mark Baker Jun 29 '17 at 16:50
  • Actually `require` is not a function at all. It is a language construct. Just like `switch` or `echo`. – arkascha Jun 29 '17 at 16:50
  • @JonathanKuhn Yes, that was my point. – Alex Howansky Jun 29 '17 at 16:52
  • @arkascha I tend to agree considering that it introduces any code to the parent scope. Trying to recreate your own custom_require function would be pretty close to impossible as even something like reading the file and eval would be within that function's scope, not the parent. – Jonathan Kuhn Jun 29 '17 at 16:53
  • Added a simple clarification as to why I'm looking into doing this. Ruby Perl Python and NodeJS let you do this and the resulting experience is pretty good. – Carlos Vergara Jun 29 '17 at 16:59
  • Possible duplicate of [Redefine Built in PHP Functions](https://stackoverflow.com/questions/2326835/redefine-built-in-php-functions) – mleko Jun 29 '17 at 17:52

0 Answers0