Page 1 of 1

newbbie POO question - constructors

Posted: Thu May 10, 2007 10:33 am
by pedrotuga

Code: Select all

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?

Posted: Thu May 10, 2007 10:39 am
by dhrosti
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...

Code: Select all

class myClass {

  var $a;

  var $b;

  // Constructor...

  function myClass($a, $b) {

    $this->a = $a;

    $this->b = $b;

  }

}

}
Then create it as...

Code: Select all

$newclass = new MyClass($a, $b);
And the constructor will set the variables in the right place for you.

Posted: Thu May 10, 2007 10:46 am
by pedrotuga
that's quite simple.
Thank you.

Posted: Thu May 10, 2007 10:50 am
by RobertGonzalez
Constructors do not typically return values, so I would put in a secondary check of some sort, either through an object property or method...

Code: Select all

<?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';
}
?>

Re: newbbie POO question - constructors

Posted: Thu May 10, 2007 4:02 pm
by stereofrog
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.

Posted: Thu May 10, 2007 5:55 pm
by pedrotuga
Thank you everybody. Apreciated.

I must confess though that i still can't get to the point when a OOP approach saves me from some extra work as i mostly write code that is not reused.