Link to home
Start Free TrialLog in
Avatar of drakkarnoir
drakkarnoir

asked on

PHP 5 Constructors

Why is it that I cannot pass a variable to a constructor in PHP 5?

Example:

class Test {

function __construct($constructvar)
{
echo $constructvar;
}

}

$Test = new Test("hi");

if(class_exists($Test))
echo "Test has been initialized.";
else
echo "No go.";

Any ideas? Or have I forgot to remember something about constructors...
Avatar of Diablo84
Diablo84

class_exists is looking for a string name not an initialized class, you would have to do

<?php
class Test {
 function __construct($constructvar) {
  echo $constructvar;
 }
}

$Test = new Test;
$Test -> __construct("hi");

echo (class_exists('test')) ? "Test has been initialized." : "No go.";
?>
The only way you can feed it as a variable is by assigning the string name of the class like this

class Test {
 function __construct($constructvar) {
  echo $constructvar;
 }
}

$Test = Test;

echo (class_exists($Test)) ? "Test has been initialized." : "No go.";
a constructor is executed when you create an instance, so there cannot be the possibility of passing a variable. if you need to, you'll have to stick to calling a selfmade constructor method.
...or set the initial value for your variable in your properties declaration. but this abiously lacks the flexibility you are probably looking for.
ASKER CERTIFIED SOLUTION
Avatar of d_tan
d_tan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i dont see an awful lot of difference between the accepted answer and mine :S

anyone care to shed some light...
I addressed the fact that the question was actually  Why is it that I cannot pass a variable to a constructor in PHP 5? vs.  Why isn't class_exists working.  I think points could have been split.

dtan
I had thought i had highlighted the reason why it wasnt working in my first and second post

>>  class_exists is looking for a string name not an initialized class

and

>>  The only way you can feed it as a variable is by assigning the string name of the class like this...

oh well :(
I think he was more interested in why

 function __construct($constructvar) {

}

wasn't working. . . but mistakenly used class_exists .

dtan