PHP - Check if a function contains - php

I want to check if a function contains a variable called $marker.
This is what I'm trying to do:
if(function('head') contains '$marker') {
return true;
}
Is there any way to do this?

Ummm... it's not built into PHP, and, frankly, changing the files would be better, but for science reasons, I wrote a check for it. It fetches the filenames's contents every function call, so I'd recommend, if you use it more than once, to store the file's contents in another variable, but, nevertheless, this is will give you a functional view on how to do it:
<?php
function test() { $marker;}
function negativeTest() {
$noMarker;
}
function checkFunction($function, $variable, $filename) {
$file = file_get_contents($filename);
preg_match_all("/function\s+([a-z0-9_-]+)\s*\(.*?\)\s*\{((\n|.)*?)\}/im",$file,$matches);
for ($i = 0; $i < count($matches[1]); $i++) {
if ($matches[1][$i] == $function && strpos($matches[2][$i], $variable) != false) {
return true;
}
}
return false;
}
echo checkFunction("test","\$marker","index.php");
?>

Related

How to call a function with other function as argument

im just learning php
Im trying to add a log with comments to my functions output.
Right now it looks like this:
//the function
function add1($x){
if($GLOBALS['logging'] === 'on'){ $log[] = 'Adding 1 to '.$x;};
$a = $x + 1;
if($GLOBALS['logging'] === 'on'){
$return[] = $a;
$return[] = $log;
return $return;
}else{ return $a; };
};
//calling the function
if($GLOBALS['logging'] === 'on'){
$return = add1($x);
$number = $return[0];
$log = $return[1];
}else{ $number = add1($x); };
Im kinda annoyed by the fact i need to retype this if statement.
So i made a seperate function for returning the function
which looks like this:
//function
function log_return($data = 'x', $log = 'x'){
if($GLOBALS['logging'] === 'on'){
if($data !== 'x') $return[] = $data;
if($log !== 'x') $return[] = $log;
return $return;
} return $data;
};//function end
And returning it with:
return $return = isset($log) ? log_return($data, $log) : log_return($data);
Now my quastion is: Is there a way to call a function with function..
like:
call_function(add1($x));
so i can return it either with log or without..
Given the answer https://stackoverflow.com/a/2700760/5387193 - this should work:
function add1($a)
{
// add1 code goes here
}
function call_function($name, $param)
{
$name($param);
}
call_function('add1', $x);
On a side note, your variable and function names aren't very intuitive. Perhaps you should study how to write good quality readable code. I recommend reading chapter 9 of Refactoring by Martin Fowler, it's quite good. You can find a PDF version on the web.
Another note, your return statement return $return = isset($log) ? log_return($data, $log) : log_return($data); has a unnecessary assignment to $return. The code should simply read
return isset($log) ? log_return($data, $log) : log_return($data);
Yes, it is possible. To simplify:
function first($x) {
return $x+1;
}
function second($y) {
return $y+1;
}
echo second(first(1)); // Returns 3, ie. 1+1+1
As gview said in his comment, don't use global variables. Argument lists exist for several reasons, included but not limited to making code easier to read, edit, and debug. The same goes for function and variable names.
Moreover, your code is very messy. It can be consolidated:
function addTo($currentValue, $valueToAdd, $logging = 0)
{
if ($logging) {
logWrite('addTo', "Adding $valueToAdd to $currentValue");
return $currentValue + $valueToAdd;
} else {
return $currentValue;
}
}
function logWrite($operation, $message)
{
$log = getLog(); // maybe it's a file, or DB record or something
// perform the write, depending on your implementation
}
$number = addTo($someStaringValue, $someOtherValue, 1);
All of this said, logging should not control program flow. In other words, whether something is logged by the system or not should have no bearing on what your code is trying to do. I really think you need to take a broader view of what you're trying to do and break it up into components.
At best, your code should tell a logger to log info, and the logger itself should determine if logging is actually turned on. If it is, the info is logged. If not, then the code that calls on the logger still works and goes about its business.

returning from multiple points in a function

This is more or less a readability, maintainability and/or best practice type question.
I wanted to get the SO opinion on something. Is it bad practice to return from multiple points in a function? For example.
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== FALSE) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
} else {
return FALSE;
} else {
// returning false because $a->value isn't set
return FALSE;
}
}
?>
or should it be something like:
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== false) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
}
}
return FALSE
}
?>
As a matter of practice, I always try to return from ONE point in any function, which is usually the final point. I store it in a variable say $retVal and return it in the end of the function.It makes the code look more sane to me.
Having said that, there are circumstances where say, in your function as the first line you check if a var is null and if yes you are returning. In this case, there is no point in holdin on to that variable, then adding additional checks to skip all the function code to return that in the end.
So...in conclusion, both ways works. It always depends on what the situation is and what you are more comfortable with.

in a function can you retun a null to exit the function PHP

I am passing the two var's by ref to change them, and once I have changed them or one of the (8 loops) have found a positive in the string I am using, I want to exit the function, but I don't need to return anything because they are passed by ref.
I could just pass a copy of one and then ref the other one and set the var of the one that is copied = to the function and return that, but is there a cleaner way where I just call the function, the vars are set and I can move on?
function get_cat_size($urlstr, &$cat, &$size){ return null; };
$cat = get_cat_size($urlstr, &$size);
Does the first one work or not? Witch is better for readability?
Thanks for the input!
while( $i < $countz )
{
$pos = strpos($outdoor, $outdoor[$i]);
if($pos != false)
{
$cat = $outdoorID;
while( $j < $sizeArrayCount)
{
$poz = strpos($outdoor, $outdoor[$i]);
if($poz != false)
{
$size = $outdoorID;
return;
}
$j++;
}
return;
}
$i++;
}
^ so this should work yes no maybe so?
So this is one of 8 loops set up in a order because they are least important to important, with different var = different stores.
You can just return without a value:
function returnsNothing (&$a, &$b) {
return;
}
Or simpler just omit the return statement at all
function returnsNothing (&$a, &$b) {
// do something
}
Both snippets will make the function returning NULL.
Take a look at break for returning out of your for loops.
I would personally avoid returning null within a function since NULL will be returned by default when there is no return value specified. You can read more here at PHP: Returning values

How to access a member variable of different function in a codeigniter controller

//first function
function insertdigit(){
$userdigit=5;
$flag = $this->usermodel->userdigitmodel($userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->insertdigit();
}
but i get {"result":true} goes back to the function? how to access a member variable in a different member function
Try to remove echo json_encode($value); in your code.
If you need to access a parameter in several functions on your controller, you have to create it outside your function so it will be available for all your controller functions.
So, in your case it should be something like this:
class Test extends Controller
{
private $userdigit; //here you can set a default value if necessary: private $userdigit = 5
function insertdigit(){
$this->userdigit=5;
$flag = $this->usermodel->userdigitmodel($this->userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $this->userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->userdigit;
}
}
This way your userdigit variable is available for all your functions. With $this you are telling PHP that you are trying to access something inside the class.
This link contain more and useful information: http://www.php.net/manual/en/language.oop5.properties.php
Is that what you really need?
A possible solution:
function insertdigit()
{
$userDigit = 5;
$flag = $this->usermodel->userdigitmodel($userDigit);
$value = array
(
'result' => $flag
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo json_encode($value);
}
if ($flag == true)
{
return $userdigit;
}
else
{
}
}
//second function
function usedigit()
{
$data['userdigit'] = $this->insertdigit();
}
The above code, in insertdigit detects if there is an Ajax request and if so, it will echo out the json_encoded data. If you call it in an normal request, i.e. via usedigit it won't echo the json_encoded data (unless you are calling usedigit via an Ajax request).
Your question doesn't really explain what you are doing, so it's hard to explain a better solution, however, if you are trying to access a "variable" in more than one place, you should really separate your code so you have a single entry point for that variable.
Is your variable dynamic, or is it static?

"Fatal error: Cannot redeclare" when reusing xml parsing code

I have a single xml parsing function that I'm trying to call multiple times as I only need to strip a little data out and continue on.
Here is the function:
//Parse Product ID from Product Sides
function getProductSpecs($xml,$type) {
// Setup arrary
global $productspecs;
global $count;
$count = 0;
global $type_check;
$type_check = $type;
// Parse the XML
// Create the parser
if (! ($xmlparser = xml_parser_create()) )
{
die ("Cannot create name list parser");
}
// Start tag function
function first($parser, $name, $attribs) {
global $trigger;
if ($name == "PRODUCTSIDEID") {
$trigger = 1;
} elseif ($name == "PRODUCTID") {
$trigger = 1;
}
}
// data handler function
function xml($parser, $data) {
global $trigger;
global $productspecs;
global $count;
global $type_check;
if ($trigger == 1){
if ($type_check == "sideid") {
$productspecs[$count]=$data;
$count = $count + 1;
} elseif ($type_check == "productid") {
$productspecs[$count]=$data;
$count = $count + 1;
}
$trigger = 0;
}
}
// Call the handler functions
xml_set_element_handler($xmlparser, "first", "");
// Call the data handler
xml_set_character_data_handler($xmlparser, "xml");
// Parse the XML data
xml_parse($xmlparser,$xml);
// Clear parser
xml_parser_free($xmlparser);
//Return the array
return $productspecs;
}
My problem arises when this is called:
xml_set_element_handler($xmlparser, "first", "");
I get the redeclare error on:
function first($parser, $name, $attribs) {
The function only appears the one time and I'm assuming the problem occurs on the call but is there a way around this so I don't have to duplicate so much code. I'm going to have to iterate through this multiple times.
Thanks.
Defining functions inside of functions can lead to this. Each time you run getProductSpecs() it's going to try to declare first() and xml() again, and in PHP, all user functions are declared in a global scope. The best solution is to move your first() function and your xml() function outside of the main getProductSpecs() function.
Another option is to use function_exists() around your function declarations, like this:
if (! function_exists('first')) {
// Start tag function
function first($parser, $name, $attribs) {
global $trigger;
if ($name == "PRODUCTSIDEID") {
$trigger = 1;
} elseif ($name == "PRODUCTID") {
$trigger = 1;
}
}
}

Categories