php function in array broken - php

I am trying to setup an array that pulls the filename and function name to run, but it not fully working.
The code is
$actionArray = array(
'register' => array('Register.php', 'Register'),
);
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
echo '<br><br>index<br><br>';
echo 'test';
exit;
}
require_once($actionArray[$_REQUEST['action']][0]);
return $actionArray[$_REQUEST['action']][1];
Register.php has
function Register()
{
echo 'register';
}
echo '<br>sdfdfsd<br>';
But it does not echo register and just sdfdfsd.
If I change the first lot of code from
return $actionArray[$_REQUEST['action']][1];
to
return Register();
It works, any ideas?
Thanks

Change the last line to:
return call_user_func($actionArray[$_REQUEST['action']][1]);
This uses the call_user_func function for more readable code and better portability. The following also should work (Only tested on PHP 5.4+)
return $actionArray[$_REQUEST['action']][1]();
It's almost the same as your code, but I'm actually invoking the function instead of returning the value of the array. Without the function invocation syntax () you're just asking PHP get to get the value of the variable (in this case, an array) and return it.

You'll find something usefull here:
How to call PHP function from string stored in a Variable
Call a function name stored in a string is what you want...

Related

PHP function_exists not working, and returning false

So I am running PHP 5.6 on my server and I am trying to check if a function exists, when I do I type this code.
<?php
$functionName = 'SalesWeek';
if (function_exists($functionName)) {
$functionName();
} else {
echo "No function exists for ".$functionName."\n";
}
function SalesWeek(){
echo "Hello!";
}
This fails every single time that I run it. But if I take that exact same code and drop it in something else i.e phptester.net it works just fine. I am using codeigniter so I thought maybe it had to do with that so I tried changing the function to public and private to see if it made a difference. Any ideas?
function_exists() only works for top-level functions, not object methods:
<?php
function foo() { echo "foo\n"; }
class bar { function baz() { echo "baz in bar\n"; }}
var_dump(function_exists('foo'));
var_dump(function_exists('baz'));
output:
bool(true) <--foo
bool(false) <--baz
Nor will it work for nested functions:
function x() {
function y() { ... }
}
var_dump(function_exists('y')) -> bool(false)
Technically functions (in the wild) are not methods (aka "function in a class").
function_exists() does not check for class methods. It checks only for functions in the namespace you are using.
If you want to check for a class' method you need to use method_exists() http://php.net/manual/en/function.method-exists.php
Also there is an order in php is read. And it is top-to-bottom. So in your example above the function you are looking for does not exists before you define it on the last 3 lines of your code.
**BELOW EXAMPLE IS NOT TRUE, SEE THE EDIT **
function_exists('myFunc'); //returns false
function myFunc(){}
function_exists('myFunc'); //returns true
Hope this clears things a bit
EDIT:
I just discovered a very strange behavior (PHP 5.6)
if the function is in the same file:
<?php
function_exists('myFunc'); //returns TRUE
function myFunc(){}
function_exists('myFunc'); //returns TRUE
if it's not in the same file:
<?php
echo function_exists('myFunc') ;//returns FALSE
include 'test2.php';//assume myfunc() is defined in this file
echo function_exists('myFunc');//returns TRUE
SO my first answer above seems to be only partially true.
PHP reads your code top to bottom, but it reads whole files. So if you define your function in the same file it will "exist" for php. If it's in another file, that file must first be loaded/included.
If you are using namespaces be sure to include the full qualified name:
function_exists('\myNameSpace\myFunctionName');

PHP: how to check if a given file has been included() inside a function

I have a PHP file that can be include'd() in various places inside another page. I want to know whether it has been included inside a function. How can I do this? Thanks.
There's a function called debug_backtrace() that will return the current call stack as an array. It feels like a somewhat ugly solution but it'll probably work for most cases:
$allowedFunctions = array('include', 'include_once', 'require', 'require_once');
foreach (debug_backtrace() as $call) {
// ignore calls to include/require
if (isset($call['function']) && !in_array($call['function'], $allowedFunctions)) {
echo 'File has not been included in the top scope.';
exit;
}
}
You can set a variable in the included file and check for that variable in your functions:
include.php:
$included = true;
anotherfile.php:
function whatever() {
global $included;
if (isset($included)) {
// It has been included.
}
}
whatever();
You can check if the file is in the array returned by get_included_files(). (Note that list elements are full pathnames.) To see if inclusion occurred during a particular function call, check get_included_files before and after the function call.

Include PHP file with parameter

newbie in PHP here, sorry for troubling you.
I want to ask something, if I want to include a php page, can I use parameter to define the page which I'll be calling?
Let's say I have to include a title part in my template page. Every page has different title which will be represented as an image. So,
is it possible for me to call something <?php #include('title.php',<image title>); ?> inside my template.php?
so the include will return title page with specific image to represent the title.
thank you guys.
An included page will see all the variables for the current scope.
$title = 'image title';
include('title.php');
Then in your title.php file that variable is there.
echo '<h1>'.$title.'</h1>';
It's recommended to check if the variable isset() before using it. Like this.
if(isset($title))
{
echo '<h1>'.$title.'</h1>';
}
else
{
// handle an error
}
EDIT:
Alternatively, if you want to use a function call approach. It's best to make the function specific to activity being performed by the included file.
function do_title($title)
{
include('title.php'); // note: $title will be a local variable
}
Not sure if this is what you're looking for, but you can create a function to include the file and pass a variable.
function includeFile($file, $param) {
echo $param;
include_once($file);
}
includeFile('title.php', "title");
In your included file, you could do this:
<?php
return function($title) {
do_title_things($title);
do_other_things();
};
function do_title_things($title) {
// ...
}
function do_other_things() {
// ...
}
Then, you could pass the parameter as such:
$callback = include('myfile.php');
$callback('new title');
Another more commonly used pattern is to make a new scope for variables to be passed in:
function include_with_vars($file, $params) {
extract($params);
include($file);
}
include_with_vars('myfile.php', array(
'title' => 'my title'
));
The included page will already have access to those variables defined prior to the include. If you require include specific variables, I suggest defining those variables on the page to be included

PHP include/require within a function

Is it possible to have return statements inside an included file that is inside a function in PHP?
I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.
As in
function sync() {
include_once file.php;
echo "Test";
}
file.php:
...
return "Something";
At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?
Sorry for the slightly odly worked question, hope I made it make sense.
Thanks,
You can return data from included file into calling file via return statement.
include.php
return array("code" => "007", "name => "James Bond");
file.php
$result = include_once "include.php";
var_dump("result);
But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.
EDIT:
I am looking to do this as I have lots
of functions in separate files and
they all have a large chunk of shared
code at the top.
In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.
return will not work, but you can use the output buffer if you are trying to echo some stuff in your include file and return it somewhere else;
function sync() {
ob_start();
include "file.php";
$output = ob_get_clean();
// now what ever you echoed in the file.php is inside the output variable
return $output;
}
I don't think it works like that. The include does not simply put the code in place, it also evaluates it. So the return means that your 'include' function call will return the value.
see also the part in the manual about this:
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it.
The return statement returns the included file, and does not insert a "return" statement.
The manual has an example (example #5) that shows what 'return' does:
Simplified example:
return.php
<?php
$var = 'PHP';
return $var;
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>
I think you're expecting return to behave more like an exception than a return statement. Take the following code for example:
return.php:
return true;
?>
exception.php:
<?php
throw new exception();
?>
When you execute the following code:
<?php
function testReturn() {
echo 'Executing testReturn()...';
include_once('return.php');
echo 'testReturn() executed normally.';
}
function testException() {
echo 'Executing testException()...';
include_once('exception.php');
echo 'testException() executed normally.';
}
testReturn();
echo "\n\n";
try {
testException();
}
catch (exception $e) {}
?>
...you get the following output as a result:
Executing testReturn()...testReturn() executed normally.
Executing testException()...
If you do use the exception method, make sure to put your function call in a try...catch block - having exceptions flying all over the place is bad for business.
Rock'n'roll like this :
index.php
function foo() {
return (include 'bar.php');
}
print_r(foo());
bar.php
echo "I will call the police";
return array('WAWAWA', 'BABABA');
output
I will call the police
Array
(
[0] => WAWAWA
[1] => BABABA
)
just show me how
like this :
return (include 'bar.php');
Have a good day !

some kind off variable problem within php class

I have this in my class
When the second function is called php errors with
wrong datatype and only variables can be past by reference.
I don't know what they mean by that
This code comes from php.net
If the same code is outside the class it executes fine
What am I doing wrong here, if I am working within a class?
$extensiesAllowed= array();
function __construct() {
$this->extensiesAllowed= array("txt", "pdf");
$this->fileName= $_FILES['file'];
}
private function isAllowedExtensie($fileName) {
return in_array(end(explode(".", $fileName)), $this->extensiesAllowed);
}
public function check_upload() {
if($this->fileName['error'] == UPLOAD_ERR_OK) {
if(isAllowedExtensie($this->fileName['name'])) {
return true;
}
}
}
the php error shows
Array
(
[bestandsNaam] => ACCOUNT INFO.txt
[extensiesAllowed] =>
)
Thanks, Richard
try putting the end and explode in seperate statements - I think end() may read by reference. In any case, it will help you figure out what line is causing you problems if it doesnt fix it.
In the second function/method you should call should be calling isAllowedExtensie as $this-> isAllowedExtensie()
if($this->isAllowedExtensie($this->fileName['name'])) {
Edit: forget my second comment..

Categories