there are function a and function b in test.php,which will be called by the parameter of "act" in $_GET,and it have a default value if there is no value of "act"
<?php
if(isset($_GET['act'])&&$_GET['act']){
$act=$_GET['act'];
}else{
$act='a';
}
function a(){
echo('this is a');
}
function b(){
echo('this is b');
}
$act();
?>
if i run the code below,it will call function a and function b in test.php,
<?php
include ("test.php");
b();
?>
how can it just call function b only? i don't want to change the default value of "act",because it will be used by other system
thanks
You're telling it to call two functions. When you include("test.php"), the line at the end calls function a:
$act();
Then in your other source file, you're explicitly calling b():
b();
You need to remove one of these calls.
By the way, what you're doing is extremely dangerous, not sanitizing your input. As a trivial example, let's say your second source file is called second.php and the user types the following url:
http://yourserver.com/second.php?act=phpinfo
They will get a printout out of your Apache installation data, including all modules you have loaded, etc. There are even more dangerous things they probably could do that I'm not considering off the cuff. You need an explicit whitelist of legal actions that you actually check and validate against.
you may define some variable/constant inside the included file, and when it exists, don't call $act()
<?php
if(isset($_GET['act'])
&&
$_GET['act']
&&
in_array($_GET['act'],array('a','b'))
){
$act=$_GET['act'];
}else{
$act='a';
}
function a(){
echo('this is a');
}
function b(){
echo('this is b');
}
if(!defined('FOO')){
$act();
}
?>
.......
<?php
if(!defined('FOO')){
define('FOO',true);
}
include ("test.php");
b();
?>
Related
i am trying to find out a way to pass non global variables to included document.
page1.php
function foo()
{
$tst =1;
include "page2.php";
}
page2.php
echo $tst;
How can i make that variable be visible ? and how would i do this php templating so i can split header body and footer for html pages. like in a wordpress it has custom wp functions but i dont see them declaring external files to use them.
big thanks in advance.
I think you are not exactly understanding what is going on. Page 1 should probably be doing the echoing. So you include page 2 and the foo function is now available. You need to call it so that it actually executes. Use the global keyword to bring a global variable into the function scope. Then you can echo it.
page1:
include "page2.php";
foo();
echo $test;
page 2:
function foo()
{
global $test;
$test =1;
}
Variables in a function are not seen outside of them when they are not global. But an include in a function should be seen inside the second file.
$test="Big thing";
echo "before testFoo=".$test;
// now call the function testFoo();
testFoo();
echo "after testFoo=".$test;
Result : *after testFoo=Big thing*
function testFoo(){
// the varuiable $test is not known in the function as it's not global
echo "in testFoo before modification =".$test;
// Result :*Notice: Undefined variable: test in test.php
// in testFoo before modification =*
// now inside the function define a variable test.
$test="Tooo Big thing";
echo "in testFoo before include =".$test;
// Result :*in testFoo before include =Tooo Big thing*
// now including the file test2.php
include('test2.php');
echo "in testFoo after include =".$test;
// we are still in the function testFoo() so we can see the result of test2.php
// Result :in testFoo after include =small thing
}
in test2.php
echo $test;
/* Result : Tooo Big thing
as we are still in testFoo() we know $test
now modify $test
*/
$test = "small thing";
I hope that made the things more clear.
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');
Is it possible to call only the specific function from another file without including whole file???
There may be another functions in the file and don't need to render other function.
The short answer is: no, you can't.
The long answers is: yes, if you use OOP.
Split your functions into different files. Say you are making a game with a hero:
Walk.php
function walk($distance,speed){
//walk code
}
Die.php
function die(){
//game over
}
Hero.php
include 'Walk.php';
include 'Die.php';
class Hero(){
//hero that can walk & can die
}
You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.
One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.
In PHP it's not available to get only a little part of a file.
Maybe this is a ability to use only little parts of a file:
I have a class that calls "utilities". This I am using in my projects.
In my index.php
include("class.utilities.php")
$utilities = new utilities();
The file class.utilities.php
class utilities {
function __construct() {
}
public function thisIsTheFunction($a,$b)
{
$c = $a + $b;
return $c;
}
}
And then i can use the function
echo $utilities->thisIsTheFunction(3,4);
include a page lets say the function is GetPage and the variable is ID
<?php
require('page.php');
$id = ($_GET['id']);
if($id != '') {
getpage($id);
}
?>
now when you make the function
<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>
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
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 !