...

View Full Version : global array or object(without class)



skywaves
01-11-2010, 03:06 AM
Hi

i came across config file of moodle and saw that most of the code in config is as follows



/// Moodle Configuration File

unset($CFG);

$CFG->dbtype = 'mysql';
$CFG->dbhost = 'localhost';
$CFG->dbname = 'moodle';
$CFG->dbuser = 'user';
$CFG->dbpass = 'pass';
$CFG->dbpersist = false;
$CFG->prefix = '';

$CFG->wwwroot = 'http://moodle.local';
$CFG->dirroot = 'C:\eclipsepdt\workspace\moodle';
$CFG->dataroot = 'C:\eclipsepdt\workspace\moodle\moodledata';
$CFG->admin = 'admin';

$CFG->directorypermissions = 00777; // try 02777 on a server in Safe Mode

$CFG->passwordsaltmain = '@#$!%^&!@etLflh4+3Q?}@3)(~=LkS[2RfpOezD';

require_once("$CFG->dirroot/lib/setup.php");
// MAKE SURE WHEN YOU EDIT THIS FILE THAT THERE ARE NO SPACES, BLANK LINES,
// RETURNS, OR ANYTHING ELSE AFTER THE TWO CHARACTERS ON THE NEXT LINE.



in another package config settings were like





$config[dbtype] = 'mysql';
$config[dbhost] = 'localhost';
$config[dbname] = 'project';
$config[dbuser] = 'user';
$config[dbpass] = 'pass';
$config[dbpersist] = false;
$config[prefix] = '';



i have used code like second example but i have never seen code like first example. from the look it is object but it is without class and i see no difference in using associative array instead of this.

am i missing something?

i checked php manual but could not find answer.

please guide me in right direction

thanks

Fou-Lu
01-11-2010, 04:44 AM
The first is object based, though I'm not sure how it actually works since the first line is to destroy the variable $CFG. $CFG is an instance of an object, if I had to guess it would probably be called Config or something similar for its classname.
Objects have a benefit, they can be controlled. Unlike array's, you can force you're objects to reject random stuff (by default, they do not, you need to override the __set method to throw an exception). This is to retain backwards compatibility with PHP4.

Objects have a slightly stronger approach; with PHP's datatype weakness arrays and objects are the only two things that can be controlled in functions / methods parameter signatures. This is a huge advantage. As stated above though, arrays cannot be guaranteed to contain what is expected, unlike a class.


function doSomethingWithArray(array $a)
{
// Do something with an array. We don't know whats in it though, so we need to check
// each offset individually
}

function doSomethingWithObject(IConfiguration $config)
{
// This throws an exception if the provided argument is not a type of IConfiguration.
// Interfaces and classes guarantee what we expect, so we don't need to check.
}

skywaves
01-11-2010, 05:09 AM
Thanks for the reply. now picture is more clear.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum