PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
kknight
Forum Newbie
Posts: 4 Joined: Tue Nov 15, 2005 7:45 pm
Location: CA, USA
Post
by kknight » Wed Nov 16, 2005 3:51 pm
Can I just call a function in another PHP script, instead of evaluating the whole php script.
For example, a.php calls a function foo() in b.php.
b.php is like this:
Code: Select all
<?
echo "Hello";
function foo() {
echo "I am foo.";
}
?>
a.php just wants to call the function foo() in b.php, but don't want to execute
echo "Hello"; in b.php. Is it possible in PHP?
Thanks.
HawleyJR: Please use tags when Posting PHP Code In The Forums
Nathaniel
Forum Contributor
Posts: 396 Joined: Wed Aug 31, 2005 5:58 pm
Location: Arkansas, USA
Post
by Nathaniel » Wed Nov 16, 2005 3:53 pm
Possible, yes. I would highly recommend putting your functions in seperate files, though.
ody
Forum Contributor
Posts: 147 Joined: Sat Mar 27, 2004 4:42 am
Location: ManchesterUK
Post
by ody » Wed Nov 16, 2005 4:14 pm
You could create a class in b.php file then call the function you need in a.php i.e.
Code: Select all
require_once('b.php');
$foo = new bar();
$bar->foo();
unset($bar);
and in b.php have:
Code: Select all
class bar
{
function foo()
{
echo 'I am foo.';
}
}
Jenk
DevNet Master
Posts: 3587 Joined: Mon Sep 19, 2005 6:24 am
Location: London
Post
by Jenk » Wed Nov 16, 2005 4:53 pm
kknight wrote: Can I just call a function in another PHP script, instead of evaluating the whole php script.
For example, a.php calls a function foo() in b.php.
b.php is like this:
Code: Select all
<?
echo "Hello";
function foo() {
echo "I am foo.";
}
?>
a.php just wants to call the function foo() in b.php, but don't want to execute
echo "Hello"; in b.php. Is it possible in PHP?
Thanks.
HawleyJR: Please use tags when Posting PHP Code In The Forums No.
You would need to have the function definition on it's own, or with other function/class definitions and no script.
if a.php consists of:
Code: Select all
<?php
echo "Hello!\n";
function foo ()
{
echo "I am foo!";
}
?>
and you wanted b.php to use foo(), then you must include a.php:
And the output will be:
The 'best practice' is to have your functions in a seperate file from any script, so you can include them at will and they will not ouput anything unless you explicity call upon a function/class to do so.