unrequire a file once it's been required in PHP - php

Suppose I do
require('lol.php');
whereby lol.php contains the following function declaration
function lolfunc(){
}
is it possible to "unrequire" lol.php such that I can then require another file
require('lol2.php');
whereby lol2.php contains a function with the same name previously declared in lol.php:
function lolfunc(){
echo "this is lol2 biyotch";
}
and have lolfunc() be the one declared in lol2.php? eg if I call lolfunc() it'll echo "this is lol2 biyotch"??

My answer: don't do that.
Try to work with the original author to include the functions you need into a patched version of the old code and then use that patched version everywhere.
If you can't do that, find out how big a job it would actually be to update all the code to new version. Start with white-box analysis: see what's changed in terms of interfaces, data structures et al. Then examine the calling code to see whether the caller cares about any of the things that have changed.
If you can't even do that, use namespacing or some other form of wrapping so that you can include both libs. However, make sure any initialisaton or setup is done on both libs!

What you should do, is to include the required (sets) of files based on conditional clauses, instead of trying to "unrequire".
So:
if($flag_use_oldver)
{
include("oldver.php");
}
else
{
include("newver.php");
}
If you want a more sophisticated solution, of course you could try to have a wrapper class hierarchy that will extend/override as required, but I think that is a bit over-engineering for a pretty straightforward problem statement.

Related

PHP/Wordpress, Childthemes and functions already defined

I'm wondering (I have full access to the serve in case it's a php.ini setting) if there's anyway to "disable parsing of functions if a function was already defined" instead of throwing an error/notice about it?
For example /www/main/deep/file/file.php has:
function homepage_filter_get_map () {
// example1
$generic_filter_array = td_generic_filter_array::get_array();
}
and in /www/main-child/custom.php has, which is called/included/parsed before the file above:
function homepage_filter_get_map () {
//do nothing
}
Essentially, I'm looking for a way to suppress any and all errors outputting about already defined functions while silently ignoring functions that might have the same exact name, but already parsed/defined.
My problem is that the theme I'm using doesn't have full support for Wordpress child themes, just loop files mainly. I know I can just tweak the original files but I want the ability to be able to keep the theme updated without erasing all of our custom tweaks every-time.
Note: Yes, I know you can conditionally call functions, but again I'm looking for a way to do this without editing any of the "main" files since any tweaks done to those get overwritten when updating the parent theme.
if(!(function_exists('homepage_filter_get_map'))){
function homepage_filter_get_map(){
//do code
}
}
This checks if the function 'homepage_filter_get_map' exists. If it doesn't, create the function.

PHP Functions from included files don't execute on Web Server

I am in the process of migrating a site from my personal dev server onto Windstream's business hosting server. I've already run into the issue of having developed using PHP 5.4 only to find out that my static functions won't work on WS's 5.1.4 installation. I've since fixed those issues and am not facing one that I can't seem to find any help for on the internet.
All of the static functions I was using have been rewritten as functions outside the class scope. Instead of having
class Product{
...
public static function myFunction(){}
...
}
I now have
function myFunction(){}
class Product{...}
in my included Product.php file.
However, when I try to call myFunction() from my code, nothing happens. I know the nothingness comes from WS's error handling, but the point is, the function isn't working. To verify this, I have taken the following steps:
Inserted the line echo "entered included"; immediately following the <?php in Product.php. This prints "entered included" on the index page, indicating that my include is working. I have done the same thing before the final ?> with the same results, so I don't think it's getting hung up inside the included file.
I have changed myFunction() in the included file to be simply
function myFunction(){echo "myFunction works";}
A call to myFunction() still makes nothing happen.
I have moved myFunction() to the including file (myFunction() now lives in index.php instead of Product.php; index includes Product.php). This time, myFunction() executes without issue.
To my 'hack it til it does what it should' sensibilities, this tells me that the server is having a problem with functions that are declared in files that are included; honestly, though, I have absolutely no clue what's going on, and any help would be appreciated. Their website is currently down, and they were expecting it to only be offline for a day, so I'll try pretty much anything short of sacrificing a fatted calf.
I know I should be posting more specific code, but since this is a customer's actual website, I'm trying to put as little of the actual code out here as is possible. I'm happy to append specific sections of code to this entry as they are requested for clarification.
Thanks in advance for your consideration.
#Rottingham: First, thanks for the 3v4l link. Second, my assumption about static methods in 5.4 vs 5.1.4 came from this line of php.net's page on static members and methods:
"As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static)."
src - http://www.php.net/manual/en/language.oop5.static.php
Since my version and the server version were on different sides of the 5.3 mark mentioned, I incorrectly assumed that this was my problem.
Third, when I get in from my day job, I'll update my code to show errors and update this post if a solution has not yet been found.
Ultimately, my problem isn't with using static methods (since I don't have them anymore) but with using any function that is declared in an included .php file.

Reloading a Class

I have a PHP daemon script running on the command line that can be connected to via telnet etc and be fed commands.
What it does with the command is based on what modules are loaded, which is currently done at the start. (psuedocode below for brevity)
$modules = LoadModules();
StartConnection();
while(true){
ListenForCommands();
}
function LoadModules(){
$modules = Array();
$dir = scandir("modules");
foreach($dir as $folder){
include("modules/".$folder."/".$folder.".php");
$modules[$folder] = new $folder;
}
}
function ListenForCommands(){
if(($command = GetData())!==false){
if(isset($modules[$command])){
$modules[$command]->run();
}
}
}
So, an example module called "bustimes" would be a class called bustimes, living in /modules/bustimes/bustimes.php
This works fine. However, I'd like to make it so modules can be updated on the fly, so as part of ListenForCommands it looks at the filemtime of the module, works out if it's changed, and if so, effectively reloads the class.
This is where the problem comes in, obviously if I include the class file again, it'll error as the class already exists.
All of the ideas I have of how to get around this problem so far are pretty sick and I'd like to avoid doing.
I have a few potential solutions so far, but I'm happy with none of them.
when a module updates, make it in a new namespace and point the reference there
I don't like this option, nor am I sure it can be done (as if I'm right, namespaces have to be defined at the top of the file? That's definitely workaroundable with a file_get_contents(), but I'd prefer to avoid it)
Parsing the PHP file then using runkit-method-redefine to redefine all of the methods.
Anything that involves that kind of parsing is a bad plan.
Instead of including the file, make a copy of the file with everything the same but str_replacing the class name to something with a rand() on the end or similar to make it unique.
Does anyone have any better ideas about how to either a) get around this problem or b) restructure the module system so this problem doesn't occur?
Any advice/ideas/constructive criticism would be extremely welcome!
You should probably load the files on demand in a forked process.
You receive a request
=> fork the main process, include the module and run it.
This will also allow you to run several commands at once, instead of having to wait for each one to run before launching the next.
Fork in php :
http://php.net/manual/en/function.pcntl-fork.php
Tricks with namespaces will fail if module uses external classes (with relative paths in namespace).
Trick with parsing is very dangerous - what if module should keep state? What if not only methods changed, but, for example, name of implemented interface? How it will affect other objects if they have link to instance of reloaded class?
I think #Kethryweryn is something you can try.

Is there an alternative for compiler directives in PHP in order to use app version?

Here is the thing, I have a running application and my client has been asking me to add features over time. Now he hasn't implemented all the features that I've developed, but he wants to implement one feature recently developed. The thing is that there could be some incompatibility issues between the versions of the application that I made.
I am wondering if I can add some sort of version directives to the methods of a class in php and somehow execute the ones that match with the web application version?
I would appreciate greatly any kind of help that you could give me.
You can get PHP's currently running version from the version constant PHP_VERSION and use version_compare which might help you out with w/e you are trying to do: http://php.net/manual/en/function.version-compare.php
You can set you own version and then declare the appropriate class like this (your code need to know which copy of the class is running:
define("APPLICATION_VERSION", "1.23");
define("APPLICATION_VERSION_MAJOR", "1.");
define("APPLICATION_VERSION_MINOR", "23");
if (APPLICATION_VERSION_MAJOR == "1") {
//version 1 class declaration here
class hello {}
} else {
//not version 1 class declaration here
class hello {}
}
Create a settings.php file and add constants to it.
setting.php
// Valid constant names
define("VERSION", "1");
class.php
include('settings.php')
if (defined('VERSION') && VERSION == "1") {
//run code
}
PHP is not a compiled language; just like it's client-side siblings (HTML et al.), each file is evaluated individually each time a page must be generated. So, the concept of having something in the file processed before the rest of the file loses its value rapidly.
That said, there are some variables that can be set before this process and stay constant throughout, and those are in php.ini. These are, by the literal definition, pre-processor directives. However, I know they're not what you're looking for.

JS Lexer to detect function calls

In order to localize strings used within my javascript, I want scan all my js files for such strings.
I am using a t() function to request string translations as follows:
t("Hello world");
or with dynamic portions:
t("Hello #user", {"#user": "d_inevitable"});
I want to detect all calls to the t() function and thus gather the strings contained in the first argument in a php "build" script, but skipping the following:
function foo(t) {
t("This is not the real t, do not localize this!");
}
function bar() {
var t = function(){}; //not the real t either...
}
function zoo() {
function t() {
//This also isn't the real t() function.
}
}
t("Translate this string, because this is the real t() in its global scope");
So the simple rule here is that the t function being invokes must be in global scope in order for the first argument to qualify as a translation string.
As a rule, dynamic runtime data as first argument is not allowed. The first argument to t() must always be a "constant" literal string.
I think php codesniffer will help me do it, however all the documentation I could find on it is about enforcing code standard (or detecting violations of it). I need lower level access to its js lexer.
My question is:
Would the php codesniffer's js lexer be able to help me solve my problem?
If so how do I access that lexer?
Are there any other php libs that could help me find the calls to t()?
Please do not suggest stand-alone regular expressions as they cannot possibly solve my problem in full.
Thank you in advance.
What you are describing is basically a coding standard. Certainly, ensuring strings are localised correctly is part of many project standards. So I think PHPCS is the right tool for you, but you will need to write a custom sniff for it because nothing exists to do exactly what you are after.
The best thing to do is probably clone the PHPCS Git repo from Github and then create a new directory under CodeSniffer/Standards to contain your custom sniff. Let's say you call it MyStandard. Make sure you create a Sniffs directory under it and then a subdirectory to house your new sniff. Take a look at the other standards in there to see how they work. You'll also find it easier to copy an existing ruleset.xml file from another standard and just change the cotent to suit you. if you don't want to include any other sniffs from anywhere (you just want to run this one check over your code) then you can just specify a name and description and leave the rest blank.
There is a basic tutorial that covers that.
Inside your sniff, you'll obviously want it to check JS files only, so make sure you specify that in the supportedTokenizers member var (also in the docs). This will ensure PHP and CSS files are always ignored.
When you get down to the actual checking, you'll have full low-level access to the parsed and tokenised content of your file. There are a lot of helper functions to check things like if the code inside other scopes, or to help you move backwards and forwards through the stack looking for bits of code you need.
TIP: run PHPCS using the -v option to see the token output on your file. It should help you see the structure more easily.
If you want to really do things properly, you can even create a nice unit test for your sniff to make sure it keeps running over time.
After all this, you'd check your code like this:
phpcs --standard=MyStandard /path/to/code
And you can use a lot of integrations that exist for PHPCS inside code editors.
You might decide to add a new more sniffs to the standard to check other things, which you can then do easily using your ruleset.xml file or by writing more custom sniff classes.
I hope that helps a bit. If you do decide to write your own sniff and need help, just let me know.

Categories