Page 1 of 1
Including class variables into class.
Posted: Thu Feb 03, 2011 8:52 am
by VirtualSSX
Hello everyone, i'm new to the forums, just joined actually. Please treat me well =). Ok onto the main point now. I recently decided that I wanted to try and split my class and class variables up into seperate files but it doesn't seem to work. Can anyone help me? I'll give you an example.
///////////Variables.php file
<?php
var $hi;
var $can;
var $you;
var $help;
var $me;
?>
//////////////Class.php
<?php
class HelpPlease
{
include "Variables.php";
function BlahBlah()
{
echo $this->hi;
}
}
?>
Re: Including class variables into class.
Posted: Thu Feb 03, 2011 9:11 am
by MindOverBody
Of course it's not working. You cant put
include outside of method. If you want to use some variables inside some class, inject them through constructor parameters. Constructor is method, that will be executed upon making instance of that class. For example, you can make it like this:
variables.php
Code: Select all
<?php
$data["name"] = "bla";
$data["surname"] = "blabla";
$data["age"] = "blablabla";
?>
someclass.php
Code: Select all
<?php
class SomeClass {
private $variables = array();
public __constructor( $param ){
$this -> variables = $param;
}
}
?>
For example, your index.php:
Code: Select all
// include your variables file
include 'variables.php';
// include your class file
include 'someclass.php';
// make instance of SomeClass class and inject data array from variables.php file
$myObject = new SomeClass( $data );
I suggest you to thoroughly examine this content:
PHP: Classes and objects
PS. Please use
PHPCode option in editor header in future.
Re: Including class variables into class.
Posted: Thu Feb 03, 2011 11:48 am
by VirtualSSX
Thanks <3. Guess I can't use that for the website i'm currently working on but i'll remember to use this for all future websites i make. Thank You <3. I appreciate it.
Re: Including class variables into class.
Posted: Fri Feb 04, 2011 8:29 am
by MindOverBody
VirtualSSX wrote:Thanks <3. Guess I can't use that for the website i'm currently working on but i'll remember to use this for all future websites i make. Thank You <3. I appreciate it.
No worries, of course, there are many other ways to do this, one of them are global variables inside methods, so you can inject out-class variables in it.
Code: Select all
$data["Name"] = "bla";
$data["Surname"] = "blabla";
$data["Nickname"] = "blablabla";
class SomeClass {
public function doSomething(){
global $data;
// TODO: Do something with data variable
}
}