calling one php function from other? - php

hello i want to know how to call a function defined in one php file from some other function defined in some other php page.

do like this, in the file where you need to call the function
require_once("file_having_function_that_you_need_to_call.php");
function_name($arguments); // this function is defined in 'file_having_function_that_you_need_to_call.php' file

First you need to include that file either using
require_once or require
or
include_once or include
if the function is not in class, you will call directly.
require("file.php");
echo getUserName("1")
otherwise you have to first create object and than call method
require("file.php");
$obj = new User();
echo $obj->getUserName("1");

Use include(), require(), etc. on the other PHP file, then just put the function name followed by its arguments in parentheses.

Related

How do I get the path to script calling a method in another script?

How do I get the path to a script that is calling a method of a class defined in another script, from within the class?
That is, I'd like to make a call to a class method - defined in b.php - from a.php as:
PHP code
# a.php
require 'b.php';
$obj = new AsyncDecorator('ClassName');
$obj->Call('methodName');
... with, as previously mentioned, the class being defined in b.php similarly to this snippet:
PHP code
# b.php
class AsyncDecorator
{
public function Call($method)
{
# Currently equals to b.php - I need it to be 'a.php'
$require = __FILE__;
}
}
That is, I need to know that the calling script was a.php, and I need to do it dynamically. If I'm creating and using the AsyncDecorator class in c.php, then $require should equal to 'c.php'.
A possible solution to this problem is making either the Call() method, or the initialization of the decorator to accept a $file_path parameter in which __FILE__ is passed:
PHP code
$obj = new AsyncDecorator('ClassName', __FILE__);
$obj->Call('methodName');
This has the minor downside of requiring the file path to be passed each time this object is created, which might add unnecessary parameters and not keep its use as simple and seamless as possible.
There is a gist here with a function to get the calling class.

Function and include

I have one file called paths.php that has the following code :
<?php
$path_1="db";
$path_2="files";
?>
This file is included in other files, for example file index.php and the following include : include("paths.php");
In index.php, where I got this include, I also have the following function :
<?php
function explode($value,$separator)
{
/// Into I need take value $path_1 ///
$exp=explode("$separator","$value");
for ($i=0;$i<count($exp);$i++)
{
print "".$exp[$i]."";
}
}
?>
The problem is that I need to the read the value ($value) from the include inside the function scope. I have problems with the function, the include has to be in the function to work.
Is it possible that the function take these values and do not need the include to be inside the function, because if I don't put the include inside it doesn't take correct values?
I'm having a hard time understanding what you mean. But I noticed some problem in your code:
function explode($value,$separator)
{
explode() is a built-in PHP function. You cannot redeclare it. You need to use a different function name for your function.
If you wish to access $path_1 and $path_2 from inside a function you created, you need to use global. For example:
function custom_explode($value,$separator) {
global $path_1, $path_2;
// your other codes
echo 'I can now access $path_1: '.$path_1.' and $path_2: '.$path_2.'!';
}

php i have included a file but cant call functions which are inside class

i have included a file in another file and now i want to use on of the functions from the included file.
when i go to the included file and put a variable there the variable get passed and its all good
- that means i have includedd the right file.
but when i want to call a funcion which is inside a class
class SimpleViewer {
.
.
.
.
function whatever(){}
it just doesnt call it when i each it and writes
Fatal error: Call to undefined function display_gallery_table()...
i know for sure im in the right file because the other values passed but i just can call nothing because its insidfe the class
what am i doing wrong?
Try initiating an instance of the class first like this
$myClass = new SimpleViewer();
then call the function like this
$myClass->whatever();
$var = new SimpleViewer();
$var->whatever();
You need to create an instance of the object first;
$obj = new Class();
$obj->func();
There are many ways to call a function between classes. The first I know is a static method call. You can call function by defining class::function().
example :
public class Parent{
public static function check(){
....
....
}
}
the static caller may look alike
Parent::check()
Second way is initiate the class as the new object. From the example we can do the call like
$obj = new Parent;
$obj->check();
the rest manual of implementing this is on php manual

PHP Variable Scope Issue

In my code, I use a public load_snippet function of a class when I need to include HTML or PHP snippets. (I do this instead of a direct include_once because the directory structure varies depending on certain variables).
I had some issues with variable scopes, so I've narrowed down the problem to this: let's say I define a variable within my page:
$variable = 'Hello World!";
Then, I need load in a snippet:
$APP->load_snippet("slider");
The snippet renders perfectly, except that PHP gives an undefined variable error if I try to reference $variable in the slider code. If I directly include the php file, it works as expected, so I don't understand why I'm having this problem, since this is the load_snippet function:
public function load_snippet($snippet){
if(file_exists("app/".$this->APP_TYPE."/snippets/".$snippet.".php")){
include "app/".$this->APP_TYPE."/snippets/".$snippet.".php";
}
else{
include 'common/txt/404.txt';
}
}
Any help you can give me is much appreciated.
The file is being included within the context of the load_snippet() function, and therefore has only those variables which exist within that function. One way to modify this is to make your function accept two variables: the filename and an array of values.
public function load_snippet($snippet, $content) {
if (is_array($content)) extract($content);
if (file_exists("app/".$this->APP_TYPE."/snippets/".$snippet.".php")) {
include "app/".$this->APP_TYPE."/snippets/".$snippet.".php";
} else {
include 'common/txt/404.txt';
}
}
Then
$arr = array('variable' => 'Hello world!');
load_snippet('slider', $arr);
I think include inside a function makes no sense to me... I think that you should put in function
global $variable;
Note that include will put the code inside the function(include will be replaced by code) as i know..
The way you are doing it is an ugly one, but you can use global $variable inside the snipped to refer to the variable. However if you include the snipped inside a function or a method, you'll have to make the variables in that function/method global as well
If you need $variable inside of the App::load_snippet() method, it would probably be best to pass it in:
public function load_snippet($snippet, $var='Hello world'){
if(file_exists("app/".$this->APP_TYPE."/snippets/".$snippet.".php")){
include "app/".$this->APP_TYPE."/snippets/".$snippet.".php";
}else{
include 'common/txt/404.txt';
}
}
//do something with $var
}
You can set a default for when $variable hasn't been set. No globals, no out of scope variables.
Instead you can use the constants like define('VARIALABLE','value'). which will be available to you anywhere in your file
You are including inside a class. Which means that the included file has the same variable scope as the line of code which includes it has. TO fix this all you need to do is put
global $variable;
Above the include.

Can I have a class method include a header file for me in PHP?

Please review the example code below, I have a class file that is loaded into a config file. The config file is then loaded into any page I build. Is it possible to include a header file the way I have in the show_header() method? It doesn't seem to work so how can I achieve this result?
// Core.class.php
class Core
{
public function show_header($page_name){
require_once 'includes/header.inc.php';
}
}
// config.inc.php
require_once 'Core.class.php';
$core = New core;
// testpage.php
require_once 'config.inc.php';
$core->show_header('home');
Here is the top part of the header.inc.php file I am trying to include into the page, it seems to work including it but it breaks the way the header file works.
//header.inc.php
<?PHP
//start page timer
$session->get('user_id');
$profiler = new Profiler;
$profiler->start();
//see if site is turned on/off
$core->sitestatus($config['site_status']);
This part gives me errors like this...
Notice: Undefined variable: session in
C:\webserver\htdocs\friendproject2\includes\header.inc.php
on line 5
Fatal error: Call to a member function
get() on a non-object in
C:\webserver\htdocs\friendproject2\includes\header.inc.php
on line 5
When you're including a file from within a function it's just as if you wrote the code within that file from within that function.
e.g.
file foo.php:
<?php
echo $foo->getFoo();
file bar.php
<?php
class Foo {
public function getFoo() {return 'foo';}
}
$foo = new Foo();
function bar()
{
require 'foo.php';
}
bar();
The above will result in the following notice/error being thrown, because $foo is not known within bar().
Fatal error: Call to a member function getFoo() on a non-object in /Users/hobodave/foo.php on line 3
Edit:
I'm not sure what your "Core" class fully entails, but you could perhaps use it as a type of storage for your "globals".
e.g.
<?php
$session = new Session();
$core->session = $session;
Then your $session would be accessible in your header using $this->session
re your comment, sounds like you need a root web context object that you reference the other objects from:
$ctx = WebContext::get();
$ctx->session->get('x');
$ctx->input->get('y');
$ctx->identity->valid;
etc... this is how most web frameworks do it.
$session would need to be defined, then referenced in the included file:
// If a global variable:
global $session;
$session->get('x');
// If a member of Core:
$this->session->get('x');
yes you can do that, probably you'll want require instead of require_once, and the paths would need to be based on the current working directory or an absolute path
try adding error_reporting(E_ALL) to see if any notices are happening...
All calls you make inside the header file will be called as if they were local calls inside the show_header function. So if you want to use any global variable, you will have to use global $variablename; on the top of the included file (or in the beginning of the show_header function).
If you use a static function for the session class you wouldn't need to define it in the same file. http://php.net/manual/en/language.oop5.static.php
You are trying to access $session which is out of scope as pointed in another answer.
Since session stuff is usually global throughout most apps consider using the singleton pattern for the Session class.
This way you can do something like $session = Session::getInstance().
This lets you use the session class anywhere and you usually only one need one instance of a session class (usually). Take a look at Zend Framework for examples on singleton classes.

Categories