How to call functions from another class.
![]()
Many of my articles and videos are based on questions that I see popping up in the php forums or in emails sent to me personally.
Recently I was asked by someone how they could call a function found in one class, in another. This may seem like basic stuff to those of us who know … but please keep in mind, at one time, none of us knew anything!
Anyway, here is my video on using a function from another class in a class.
This entry was posted on Saturday, July 19th, 2008 at 10:26 pm and is filed under Beginners PHP Articles, Object Oriented PHP. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.


Thank you for this tutorial. My question is, how do you call a function from another class if the classes are both instantiated from outside the classes (out at index.php, for example)?
For example, I have my class “website”, which executes session_start() among other things. My website class also houses encryption methods.
In my “pages” class, which I instantiate to create a page, it needs access to these encryption methods.
So these are instantiated from index.php, and I can’t instantiate website class twice, since it runs code that should only be executed once per page load.
I could pass my “website” object path when instantiating “pages”, but the code:
class page
{
public $website
function __construct($website)
{
$this->website->encrypt();
}
}
Fails to work. How would one get around this?
You know what? I don’t need to use $this when referencing variables passed into the methods in classes. I think by removing “this->”, the code example will work. I answered my own question
Thanks again!
Glad I could help!!
Stefan
I have a possibly similar question about already instantiated classes. Based on what I have seen on other sites I have something like this:
—class.login.php
class login
{
var $loginID; var $role; ….
function getCurrentLogin() {$this->loginID=…. }
function displayUserOptions() {echo “Welcome “.this->name …}
}
—class.navigation.php
class navigation
{
var currentPage; var menuStructure; ….
function displayNavigation($currentLogin)
{
code to display menus;
$currentLogin->displayUserOptions();
}
—-index.php
include(class.login.php);
include(class.navigation.php);
if(!isset($_SESSION["$currentLogin"])){
$_SESSION["$currentLogin"] = new login;}
$_SESSION["$currentLogin"]->checkOrGetCurrentLogin();
if(!isset($_SESSION["$navigation"])){
$_SESSION["$navigation"] = new navigation;}
$_SESSION["$navigation"]->displayNavigation($_SESSION["$currentLogin"])
The navigation bar displays fine then I get Call to undefined method login::displayUserOptions()
Hi,
Can you repost your question on the PHP forum:
http://www.killersites.com/forums/forum/12/php/
Thanks,
Stefan