...

View Full Version : defining variables inside a class



ninnypants
03-17-2009, 04:16 AM
can I use define inside of a class to use for function input. Like this:


class DB{
define('ARRAY_A', 'associative');
define('ARRAY_N', 'numeric');

public function fetch($query, $type = ARRAY_N){
// do sql work here
}
}
$db = new DB('localhost', 'root', 'pass');

$db->fetch("select * from users", ARRAY_A);


or maybe like this


class DB{
public function fetch($query, $type = ARRAY_N){
define('ARRAY_A', 'associative');
define('ARRAY_N', 'numeric');
// do sql work here
}
}
$db = new DB('localhost', 'root', 'pass');

$db->fetch("select * from users", ARRAY_A);

Fou-Lu
03-17-2009, 04:22 AM
Use a const, its better than a define since it has a scope limitation to it.


class DB{
const ARRAY_A = 'associative';
const ARRAY_N = 'numeric';

public function fetch($query, $type = self::ARRAY_N){
// do sql work here
}
}
$db = new DB('localhost', 'root', 'pass');

$db->fetch("select * from users", DB::ARRAY_A);

ninnypants
03-17-2009, 04:42 AM
Just curious would it be possible to just use the constant without self:: or DB::


class DB{
const ARRAY_A = 'associative';
const ARRAY_N = 'numeric';

public function fetch($query, $type = ARRAY_N){
// do sql work here
}
}
$db = new DB('localhost', 'root', 'pass');

$db->fetch("select * from users", ARRAY_A);

Fou-Lu
03-17-2009, 04:48 AM
Not if its defined as a const you can't. Its a scoping issue, if you don't include the self:: or DB:: it doesn't know what you're looking for. Although its also a constant, its not a defined constant like the define() function which places it into a global scope.
If you really wanted it to, you should be able to use the value of a constant as a constant. I believe it only needs to be constant data (ie: not a variable), so you may be able to do this:


define('ARRAY_N', 'associative');
class DB
{
const ARRAY_N = ARRAY_N;
}

It seems a little redundant though, and I can't be 100% certain if that works (I'm at work and can't test atm).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum