Page 1 of 1

calling class functions

Posted: Fri Jun 17, 2005 4:02 pm
by jslavin
I'm having problems calling class functions.

"Fatal error: Call to undefined function: showusername() in /home/cts/public_html/phptest/index.php on line 15"

Whenever I try to call the class' functions.

Thanks for any help in advance!

I have a simple class in (CAdminUser.php)

///////////////////////////////////////////// CLASS CODE
//////////////////////////////////////////////////////////////

Code: Select all

<?php
session_start();

class CAdminUser
{
   var $m_id;
   var $m_username;
   var $m_password;

   function showUsername()
   {
	echo $this->m_username;
   }

   function Combine($num1, $num2)
   {
	return $this->num1 . $this->num2;
   }
}
?>
//////////////// END OF CLASS CODE

///////////////////////////////// INDEX.PHP
////////////////////////////////////////////////////

Code: Select all

<?php
session_start();

require_once('CAdminUser.php');

if(!$_SESSION['CAdminUserData'])
{
   $adminUser = new CAdminUser;
   $adminuser->id = 0;
   $adminuser->username = 'unknown';
   $adminuser->password = 'not set';

   $adminuser->showUsername();        <====== ERROR HERE
   $adminuser->Combine('hello', 'two');   <===== ERROR HERE
   $_SESSION['CAdminUserData'] = $adminuser;
   // TODO: send user to login page
}
else
{
   $theadminuser = $_SESSION['CAdminUserData'];

   echo $theadminuser->id . "<BR>";
   echo $theadminuser->username . "<BR>";
   echo $theadminuser->password . "<BR>";
}
?>
//////////// END INDEX.PHP

d11wtq | Please use

Code: Select all

tags when posting PHP code[/color]

Posted: Fri Jun 17, 2005 4:17 pm
by Chris Corbyn
Firstly... for this sort of class usage instantiate it like so:

Code: Select all

$adminUser = new CAdminUser();
Secondly $this->varname you will use inside a function should be defined as (within this class):

Code: Select all

var $varname;
In the function Combine() you don't need $this->var since they are not globally accessible to the class - they are only used in that function. Just use $var instead as normal.

Thirdly :P You're assigning values to $adminUser->username instead of $adminUser->m_username as they are in your class.

Hope that helps :)

Posted: Fri Jun 17, 2005 6:14 pm
by jslavin
Thanks, it works perfect now.

One other thing, I'm also looking at having classes within classes

ie: a CAddress class within a CPerson class... (not inherited, an actual instance)

So far i've got it working, are there any pitfalls i should watch out for? Transfering the classes page to page with embedded classes within?

Thanks again for your help!