how to call a constant by a variable - php

I have a function which I use like this
$i18n_APP = new i18n($_SERVER['DOCUMENT_ROOT'].'module/'.$modid.'/lang/lang_{LANGUAGE}.ini',
$_SERVER['DOCUMENT_ROOT'].'lang/langcache/', 'en');
$i18n_APP->setPrefix('APP'.$appid);
$i18n_APP->init();
Normally I call the function by the prefix, like this
APP($el)
Now I have to use a variable prefix, cause I use the $appid, so I can't code it like the way above.
Is there any way to make it in a dynamic way maybe like this
App.$appid($el)
Hope I could explain what I tried to do.
By the way, maybe I don't need to do it, if I find a way to "add" different languagefiles to the function. For the moment I initiate a new class for every languagefile.

I find a way to solve it
function langtag($prefix, $value)
{
return $prefix($value);
}
and
$moid=4;
echo langtag('APP'.$modid,$el)

Related

How to pass additional parameter to wordpress filter?

add_filter('wp_list_pages_excludes', 'gr_wp_list_pages_excludes');
function gr_wp_list_pages_excludes($exclude_array) {
$id_array=$array('22');
$exclude_array=array_merge($id_array, $exclude_array);
return $exclude_array;
}
I'm a newbie to wordpress. The above code works fine. But I need to pass additional argument, say $mu_cust_arg to the function gr_wp_list_pages_excludes. How can I make use of it via apply_filters, or any other methods?
Any help is appreciated.
Thanks in advance.
You can indeed add multiple arguments to a filter/action, you just need to tell WordPress how many arguments to expect
Example, which won't work:
add_filter('some_filter', function($argument_one, $argument_two) {
// won't work
});
apply_filters('some_filter', 'foo', 'bar'); // won't work
It will fail with an error that too many arguments was provided.
Instead, you need to add this:
add_filter('some_filter', function($argument_one, $argument_two) {
// works!
$arugment_one; // foo
$arugment_two; // bar
}, 10, 2); // 2 == amount of arguments expected
apply_filters('some_filter', 'foo', 'bar');
Because WP doesn't accept closures as callbacks (at least, certainly not for add_filter()) the short answer is "you can't". At least, not in a tidy way.
There are a couple of options here, depending on what you are doing. The first is the best, but you may not be able to use it:
Write a wrapper function that calls your function:
function gr_wp_list_pages_excludes_1 ($exclude_array) {
$custom_arg = 'whatever';
gr_wp_list_pages_excludes_1($exclude_array, $custom_arg)
}
This will only work if you are always passing the same custom argument in a given situation - you would write one of these wrapper functions for each different situation, and pass the name of the wrapper function to add_filter(). Alternatively, if you want it to be truly dynamic, you would need to...
Use a global variable: (Ref: Variable scope, $GLOBALS)
function gr_wp_list_pages_excludes($exclude_array) {
global $gr_wp_list_pages_excludes_custom_arg;
$id_array=$array('22');
$exclude_array=array_merge($id_array, $exclude_array);
return $exclude_array;
}
Using this approach means that you can pass any data you like into the function by assigning it to $gr_wp_list_pages_excludes_custom_arg in the global scope. This is generally regarded as bad practice and heavily frowned upon, because it makes for messy and unreadable code and leaves the memory space littered with extra variables. Note that I have made the variable name very long and specific to the function to avoid collisions - another problem with using global variables. While this will work, only use it if you absolutely have to.
Very simple!
add_filter('filter_name','my_func',10,3); //three parameters lets say..
my_func($first,$second,$third){
//............
}
then
echo apply_filters('filter_name',$a,$b,$c);

Can a PHP function dynamically know its name?

I'm trying to get a list of functions that have already run in the context of an operation. And that's where the need arised.
Is there a way to get something like this work?
function funcX()
{
echo this.nameOrSomethingHere; //outputs funcX
}
As this example demonstrates, it is possible to achieve this functionality in Javascript.
I can always go for an alternative solution for taking care of my original need like with an alternative way around as follows;
function funcX()
{
$this_function_name = "funcX";
Add_this_to_the_already_executed_functions_list($this_function_name);
}
And here, the Add_this_to_the_already_executed_functions_list functions job is to take the passed string and add it to a globally defined array so at the end of the shutdown process you can get a view of all the functions that have been run in the last page.
The above method would work, but, obviously, it's not elegant cause it's not dynamic.
It would have been nice to be able to do something like this
function funcX()
{
Add_this_to_the_already_executed_functions_list(this.????);
}
The question is if there is a way to do this in PHP?
You can use __FUNCTION__ to get the current function's name.
http://us2.php.net/manual/en/function.debug-backtrace.php
debug_backtrace will tell you that and a lot more. best for debugging, but you could use it for whatever you wanted.
Use __FUNCTION__
See 'magic constants'

How to "globalize" PHP variables?

I have a page named ChangeApprovalInfo.php - It has a function called Row_Rendered as follows;
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$RecordOwner = $this->RequestUser->CurrentValue;
echo $RecordOwner;
}
Echoing $RecordOwner gets me the data I will need for a sql query on another page....
I have another page called ChangeApprovalEdit.php - This page has
<?php include_once "ChangeApprovalinfo.php" ?>
at the top of the file.
ChangeApprovalEdit.php has a function where I need the $RecordOwner variable as defined in ChangedApprovalInfo.php
If I add "echo $RecordOwner" on the ChangeApprovalEdit.php page, I get an error saying it's an unknown variable. My understanding is that I need to "make it global" or some such business. I know very little about PHP and the pages I am editing are long and complex. (to me, at least)
What do I need to do? I know that the information I have provided might not be enough to answer the question. I don't know enough to even know exactly what I need to ask. If more information is needed, I will edit and follow up.
pastebin of the files
ChangeApprovalInfo.php = http://pastebin.com/bSRM1wwN
ChangeApprovalEdit.php = http://pastebin.com/AStG9pqb
EDIT:
Changing Row_Rendered to this seems to be more effective. I'm having trouble seeing WHERE I can later echo this variable... but I'm getting somewhere with this...
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
}
Don't echo variables from functions, which just outputs them to the standard output. return them from the function so you can use the value elsewhere as well.
function Row_Rendered() {
$RecordOwner = $this->RequestUser->CurrentValue;
return $RecordOwner;
}
Then instead of
$obj->Row_Rendered();
use
echo $obj->Row_Rendered();
and if you want to use the value elsewhere, use
$value = $obj->Row_Rendered();
You can do a couple of things:
First, you can return $RecordOwner from the function, and store its value in a variable. This method is usually preferred.
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$RecordOwner = $this->RequestUser->CurrentValue;
echo $RecordOwner;
return $RecordOwner;
}
// Store it in a variable when calling the function.
$RecordOwner = Row_Rendered();
Or, you can make it global inside the function:
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
echo $GLOBALS['RecordOwner'];
}
You can use the $GLOBALS superglobals array, like this:
function Row_Rendered() {
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
}
However, you should not do that. Instead, refactor your application so that the view in ChangeApprovalinfo.php just contains a function, which is then called with the appropriate parameters.
EDIT: Chaning Row_Rendered to this seems to be more effective. I'm having trouble seeing WHERE I can later echo this variable... but I'm getting somewhere with this...
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
}
I feel compelled to write another answer to this update. Let me demonstrate the use of globals as seen from outside that function:
$obj->Row_Rendered();
$obj->foobar();
echo $GLOBALS['RecordOwner'];
Quick, what will be echoed and where does that value come from? Well, it depends on what $obj-foobar() does. Maybe it changes the global variable. Maybe it doesn't. Who knows if the variable has been set at all? How would you trace back what happened exactly without adding a debug line after every single function call?
And that's just three lines of code. Imagine that in an application of any complexity.
Now, the same thing if I return the value from Row_Rendered:
$owner = $obj->Row_Rendered();
$obj->foobar();
echo $owner;
If the Row_Rendered method is behaving as it should (returning the owner), this code is very predictable. If you do not follow this pattern, you'll have a hell of a time getting anything done when the application grows to any halfway complex size.
Set the variable as global from within the function
$my_global_var = "old value";
function doing_stuff(){
global $my_global_var; //this will use the global variable instead of creating a local one
$my_global_var = "new value";
}
echo $my_global_var;//returns "new value"

How to check whether or not a logged-in user has access to the php script that is currently being called

I've read quite a few posts that are very similar to the question I'm about to ask, but I just wanted to be sure that there wasn't a more sophisticated way to do this. Any feedback is greatly appreciated.
I want to create a mechanism to check whether or not a logged-in user has access to the php script that is currently being called. If so, the script will continue on; if not, the script just fails out using something like die('you have no access').
I came up with two ways of accomplishing this:
(please assume my session stuff is coded/working fine - i.e. I call session_start(), set up the session vars properly and etc)
Define a global variable first, then check the global variable in a required header file. For example:
Content of current_executing_script.php:
// the role the logged in user must have to continue on
$roleNeedToAccessThisFile = 'r';
require 'checkRole.php''
Content of checkRole.php:
if ($_SESSION['user_role'] != $roleNeedToAccessThisFile) die('no access for you');
Define a function within the header file and call the function immediately after including/requiring it:
Content of checkRole.php:
function checkRole($roleTheUserNeedsToAccessTheFile) {
return ($_SESSION['user_role'] == $roleTheUserNeedsToAccessTheFile);
}
Content of current_executing_script.php:
require 'checkRole.php';
checkRole('r') or die('no access for you');
I'm wondering if there is a way to basically just pass a parameter to checkRole.php as part of the include or require construct?
Thanks in advance.
There isn't a way to pass parameters to include or require.
However the code that is included joins the program flow at the point where you include it, so it will inherit any variables that are in scope. So for example if you set $myflag=true immediately before the include, your included code will be able to check what $myflag is set to.
That said, I wouldn't suggest using that technique. Far better for your include file to contain functions (or a class) rather than code that gets run straight off. If you've included a file containing functions then you can call your functions with whatever parameters you want at any point in your program. It's much more flexible, and generally a better programming technique.
Hope that helps.
This could be a useful workaround.
Register a function in say functions.php:
function get_template_partial($relative_include_path, $scoped_parameters)
{
$base_partial_directory = get_template_directory() . '/partials/';
return include $base_partial_directory . $relative_include_path;
}
Use the $scoped_parameters in the partial /partials/role-check.php:
$args = [
'id' => $scoped_parameters['user_id']
];
// A few moments later...
return [
'role_required' => 'admin'
];
Altogether now...
$partial_return_data = get_template_partial('role-check.php', [
'user_id' => 328
]);
echo $partial_return_data['role_required']; // admin
The only thing I can remember with this is if you're using an IDE it might complain that $scoped_parameters is undefined but it's not a third world issue I suppose.
You could have the required file return an anonymous function, and then call it immediately after.
//required.php
$test = function($param)
{
//do stuff
}
return $test
//main.php
$testing = require 'required.php';
$testing($arg);
In the past, many people have disagreed with this approach. But I think it is a matter of opinion.
You can't pass _GET or _POST param via a require() or include() , but you can you first set a _SESSION key/value and pull it on the other side.

Getting method params

Lets say I have a class like:
class SomeClass{
function someAction($param1,$param2){}
}
Is there any way to get analyzing data like array('param1','param2') without actual execution of method? Preferably without php extensions or prior code analysis (fopen...)
I think you can use the Reflection class to get info about method(s) and params.
Great, thank you all, solved it with something like
$oRuleContainer = new cRuleContainer();
$rContainer = new ReflectionClass('cRuleContainer');
$rMethod = $rContainer->getMethod($aRule['method']);
$aArgs = $rMethod->getParameters();
if($aArgs){
foreach($aArgs as $refArgument){
$arrPassedArgData[$refArgument->name]=$_POST[$refArgument->name];
}
}
if(call_user_func_array(array($oRuleContainer,$aRule['method']),$arrPassedArgData)){
//success
}
More details at
http://kurapov.name/rus/technology/web/php/reflection_php_brms/

Categories