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;
}
}
?>
Including class variables into class.
Moderator: General Moderators
-
VirtualSSX
- Forum Newbie
- Posts: 2
- Joined: Thu Feb 03, 2011 8:45 am
- MindOverBody
- Forum Commoner
- Posts: 96
- Joined: Fri Aug 06, 2010 9:01 pm
- Location: Osijek, Croatia
Re: Including class variables into class.
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
someclass.php
For example, your index.php:
I suggest you to thoroughly examine this content: PHP: Classes and objects
PS. Please use PHPCode option in editor header in future.
variables.php
Code: Select all
<?php
$data["name"] = "bla";
$data["surname"] = "blabla";
$data["age"] = "blablabla";
?>
Code: Select all
<?php
class SomeClass {
private $variables = array();
public __constructor( $param ){
$this -> variables = $param;
}
}
?>
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 );
PS. Please use PHPCode option in editor header in future.
-
VirtualSSX
- Forum Newbie
- Posts: 2
- Joined: Thu Feb 03, 2011 8:45 am
Re: Including class variables into class.
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.
- MindOverBody
- Forum Commoner
- Posts: 96
- Joined: Fri Aug 06, 2010 9:01 pm
- Location: Osijek, Croatia
Re: Including class variables into class.
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.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.
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
}
}