PHP functions can be defined in 3 scopes:
1. Global scope
2. As object methods
3. As class methods
If you see a function called like:
- Code: Select all
myFunction()
Then this function must have been defined in the global scope and not inside any class definitions. E.g.
- Code: Select all
function myFunction(){
// do something
}
If you see a function called like:
- Code: Select all
MyClass::myFunction()
Then this function must have been defined as a static method inside a class definition. E.g.
- Code: Select all
class MyClass {
public static function myFunction(){
// do something
}
}
If you see a function called like:
- Code: Select all
$object = new MyClass();
$object->myFunction();
Then myFunction() must be a non-static method defined inside the MyClass definition. E.g.
- Code: Select all
class MyClass {
public function myFunction(){
// do something
}
}
So in the case of a getUser() function, in order to define a function that can be called the way you see in the examples, you must define it in the global scope. The global scope is any place that is NOT inside:
1. A class definition.
2. A function definition.
So where is a good place to define such a function in a Xataface application?
I usually create a file called functions.inc.php, then include it in the first line of my index.php file. E.g.
- Code: Select all
<?php
require_once 'functions.inc.php';
//...
df_init(..., ...)->display(); ... etc...
My getUser() function generally looks something like:
- Code: Select all
function getUser(){
static $user = -1;
if ( is_int($user) and $user == -1 ){
$auth = Dataface_AuthenticationTool::getInstance();
$user = $auth->getLoggedInUser();
}
return $user;
}
In this example I declare $user static so that it will use the same variable across the entire request (so I only actually load the user from the authentication tool the first time). This is just a performance tweak since this function is likely to be called numerous times per request.
-Steve