Jump to content

Right way of setting default data in class


Zeka
 Share

Recommended Posts

Hi.

In different modules, I have seen these two ways how default data is set

	static public function getDefaultData()
	{
		return array(
			"test" => "test"
		);
	}

	// first way
	public function __construct()
	{
		foreach (self::getDefaultData() as $key => $value) {
			$this->$key = $value;
		}
	}

	// second way
		public function __construct()
	{
		foreach (self::getDefaultData() as $key => $value) {
			$this->set($key, value);
		}
	}

Could somebody please explain what is the difference between them? 

Link to comment
Share on other sites

There is very little difference:

http://processwire.com/api/ref/wire-data/set/

This one sets the property value directly. The $key is converted to a string (e.g. $this->myString = 'my value';)

$this->$key = $value;

This one uses the method set() to set both a key and a value for you. I'm not sure if the $key is manipulated in anyway behind the scenes, e.g make it 'property' friendly. I've had a quick look and couldn't find anything to that effect.

$this->set($key, value);

 

You can also do (Set a property using array access) :

$this[$key] = $value;

 

Edit:

Reading your thread title, there is no right way. All ways are correct and are documented ?

Edited by kongondo
  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...