PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
class myClass{
var $a;
var $b;
function doFoo(){
...
}
}
This is a dummy question. Can anybody tell me how would the constructor so i make sure that when a myClass type obect is created both $a and $b are defined?
Another question:
In case $a or $b are not defined when the object is created, what's the best ( or typical ) practice here? return false, raise an exception, other?
the constructor must have the same name as the class, so that when the class is instatiated, the constructor is also called. then within that constructor, you set the variables...
<?php
class myClass
{
var $a;
var $b;
var $isSet = false;
// Constructor...
function myClass($a, $b)
{
if (!empty($a) && !empty($b))
{
$this->a = $a;
$this->b = $b;
}
$this->checkSet();
}
function checkSet()
{
$this->isSet = (!is_null($this->a) && !is_null($this->b)) ? true : false;
}
}
$a = 'house';
$b = 'pink';
$cl = new MyClass($a, $b);
if ($cl->isSet)
{
echo 'There are values set for a and b.';
}
else
{
echo 'a or b is not set';
}
?>
pedrotuga wrote:
In case $a or $b are not defined when the object is created, what's the best ( or typical ) practice here? return false, raise an exception, other?
You cannot return anything from the constructor, therefore exception is the best (and sometimes the only) possibility.