Page 1 of 1

Class question

Posted: Sat Dec 02, 2006 9:14 am
by bokehman

Code: Select all

class MyClass
{
	var $MyArray = array(1,2,3);
	
	function MyMethod()
	{
		$this->IsBasic = 'like me!';
	}
}
If I want to store $MyArray in a file different from the one that holds the class in your opinion what is the best way to load it?

Posted: Sat Dec 02, 2006 9:21 am
by Oren
It really depends. You'll need to tell more.
For now, check out file() and parse_ini_file() :wink:

Posted: Sat Dec 02, 2006 12:55 pm
by bokehman
Oren wrote:It really depends. You'll need to tell more.
For now, check out file() and parse_ini_file() :wink:
I know how to open a file. I am asking specifically what would be the best way to do this in class context so I can store the variables used by the class in a seperate file.

Posted: Sat Dec 02, 2006 12:59 pm
by Chris Corbyn
Inject it manually:

Code: Select all

class MyClass
{
        var $MyArray = array();
       
        function setArray($array)
        {
                $this->MyArray = (array)$array;
        }
}

require_once "/path/to/array/file.php"

$obj = new MyClass();
$obj->setArray($array_in_file);

Posted: Sat Dec 02, 2006 1:02 pm
by aaronhall
Are you trying to write the object's properties to a file (serialize)? Or are you trying to pass one object's properties to another?

Posted: Sat Dec 02, 2006 1:14 pm
by bokehman
d11wtq wrote:Inject it manually
If I do it like that I will end up with two copies of the variable, one in the object and one in global scope. I don't want that, the array is too big.

Posted: Sat Dec 02, 2006 1:30 pm
by Flamie
pass it by reference then ;o

Posted: Sat Dec 02, 2006 1:32 pm
by Chris Corbyn
bokehman wrote:
d11wtq wrote:Inject it manually
If I do it like that I will end up with two copies of the variable, one in the object and one in global scope. I don't want that, the array is too big.
Not strictly true.

PHP will not "copy" anything in memory until you actually make changes to the value. Copy-on-write.

Passing by reference will help if you are writing to the array though.

Posted: Sat Dec 02, 2006 1:39 pm
by timvw
A class definition is required to be in one (and only one) file. So as already mentionned, you'll have to inject it... Personally i'd choose to do that in the constructor...

Code: Select all

public class Foo {
 private $foo;
 public Foo() {
  $this->foo = file_get_contents('whatever.php');
 }
}