Can a PHP function dynamically know its name? - php

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'

Related

how to call a constant by a variable

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)

Call to undefined function Laravel

I have problem when I'm checking if collection is empty or not, Laravel gives me error
"Call to undefined method
Illuminate\Database\Query\Builder::isEmpty()".
Tho it work in other Controller, but when controller is in Sub folder is suddenly stops working.
Here is my code:
$group = UserGroup::where('id', $request->group_id)->first();
if($group->isEmpty()){ // I get error from here
return redirect()->back();
}
One of the most popular way of debugging in PHP still remains the same – showing variables in the browser, with hope to find what the error is. Laravel has a specific short helper function for showing variables – dd() – stands for “Dump and Die”, but it’s not always convenient. What are other options?
Note the below mentioned methods are to find where our class fails and what are all the conditions that are available after our query executes. What is our expected result before printing it. This methods are the best methods to find out the error as required by is.
First, what is the problem with dd()? Well, let’s say we want to get all rows from DB table and dump them:
$methods = PaymentMethod::all();
dd($methods);
We would see like this:
But you get the point – to see the actual values, we need to click three additional times, and we don’t see the full result without those actions. At first I thought – maybe dd() function has some parameters for it? Unfortunately not. So let’s look at other options:
var_dump() and die():
Good old PHP way of showing the data of any type:
$methods = PaymentMethod::all();
var_dump($methods);
die();
What we see now:
But there’s even more readable way.
Another PHP built-in function print_r() has a perfect description for us: “Prints human-readable information about a variable”
$methods = PaymentMethod::all();
print_r($methods);
die();
And then go to View Source of the browser… We get this:
Now we can read the contents easily and try to investigate the error.
Moreover, print_r() function has another optional parameter with true/false values – you can not only echo the variable, but return it as string into another variable. Then you can combine several variables into one and maybe log it somewhere, for example.
So, in cases like this, dd() is not that convenient – PHP native functions to the rescue. But if you want the script to literally “dump one simple variable and die” – then dd($var) is probably the fastest to type.

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);

Best way to carry & modify a variable through various instances and functions?

I'm looking for the "best practice" way to achieve a message / notification system. I'm using an OOP-based approach for the script and would like to do something along the lines of this:
if(!$something)
$messages->add('Something doesn\'t exist!');
The add() method in the messages class looks somewhat like this:
class messages {
public function add($new) {
$messages = $THIS_IS_WHAT_IM_LOOKING_FOR; //array
$messages[] = $new;
$THIS_IS_WHAT_IM_LOOKING_FOR = $messages;
}
}
In the end, there is a method in which reads out $messages and returns every message as nicely formatted HTML.
So the questions is - what type of variable should I be using for $THIS_IS_WHAT_IM_LOOKING_FOR?
I don't want to make this use the database. Querying the db every time just for some messages that occur at runtime and disappear after 5 seconds just seems like overkill.
Using global constants for this is apparently worst practice, since constants are not meant to be variables that change over time. I don't even know if it would work.
I don't want to always pass in and return the existing $messages array through the method every time I want to add a new message.
I even tried using a session var for this, but that is obviously not suited for this purpose at all (it will always be 1 pageload too late).
Any suggestions?
Thanks!
EDIT: Added after I caused some confusion with the above...
The $messages array should be global: I need to be able to add to it through various different classes as well as at the top-level of the whole script.
The best comparison that comes to mind is to use a database to store all the messages that occur at runtime, and when it's output-time, query the database and output every message. The exception to this comparison is just that the lifetime of the $messages array is the page load (they accumulate during page load, and vanish right after).
So, for example, say I have 10 different actions running one after the other in the script. Each one of these actions make use of a different class. Each one of these classes should be able to post to $messages->add(). After all 10 actions have run, it's "output time", and the $messages array can contain up to 10 different messages which were added via all the different classes.
I hope this clarifies it a bit.
I'm not exactly clear about what you want to do, but a good way would be to simply use a private variable:
class messages {
private $messages = array();
public function add($new) {
$this->messages[] = $new;
}
public function output() {
// Whatever; e.g. a foreach loop that echoes all the messages
}
}
I think you need either a instance field.

how to call a php class function directly using ajax?

Is it possible to call a php class function DIRECTLY using ajax?
Something like below... except ajax...
myclass::myfunction();
I've been using the jquery library to work with AJAX.
$.get('control.php', {func: funcName, arg1: arg1});
The above is similar to what I'm trying to achieve MINUS the control.php;
I'm not sure if this is even possible, but I just thought it would be nice to skip the landing page (control.php) that recieves the funcName. I have a bunch of conditional statements that sort out what class function to run based on the funcName recieved.
It seems kind of silly to do this, to have a separate page just to handle function calls.
Is there a better way?
No.
If this were possible, it would be a gaping security hole.
No. You can't invoke a method directly that way.
You could use routing (like the technique used in CodeIgniter and CakePHP) but that's just syntactic sugar that does the same thing -- control your routes to actions.
It is not possible because of a simple reason. How should the AJAX knows, where to find the function. It needs to have a URL to locate the function so it doesn't work without a php file in between.
No for security reasons but there is no reason why you can't do something like this
function run($args){
//do stuff
}
echo run($_REQUEST);
//or
echo run($REQUEST['name']);

Categories