Is this the correct way of initializing the variables using constructor?
class Customer
{
public $custId;
public $custName;
function _construct()
{
$this->custId = 'Eazy01';
$this->custName = 'EazyLearnKaloor';
}
function DisplayDetails()
{
echo "$custId<br>";
echo "$custName";
}
}
$obj = new Customer();
$obj->DisplayDetails();
You need to use double undersores as in __construct()
.
class Customer
{
public $custId;
public $custName;
function __construct()
{
$this->custId = 'Eazy01';
$this->custName = 'EazyLearnKaloor';
}
function DisplayDetails()
{
echo "$this->custId<br>"; // use $this here
echo "$this->custName"; // use $this here
}
}
$obj = new Customer();
$obj->DisplayDetails();
Also you could pass variables to constructor:
function __construct($id, $name)
{
$this->custId = $id;
$this->custName = $name;
}
Then when initialising new class you can do:
$var = new Customer('Eeazy01', 'EazyLearnKaloor');
Yes...but the constructor in PHP is named __construct()
Also, you should use Getters and Setters for your Attributes and make them protected or private
You need to use a double underscore: __construct
and when you want to print your variables you have to use $this->propertyName
. The rest of your code is correct.
class Customer
{
public $custId;
public $custName;
function _construct($custId = '', $custName = '')
{
$this->custId = $custId;
$this->custName = $custName;
}
function DisplayDetails()
{
$content = $this->custId . "<br />";
$content .= $this->custName;
echo $content;
}
}
$obj = new Customer();
$obj->DisplayDetails();
If you use this way of coding you don't have to pass parameters to the constructor. You could use:
$obj = new Customer();
$obj->DisplayDetails();
and
$obj = new Customer('Hello', 'World');
$obj->DisplayDetails();
But also
$obj = new Customer(12);
$obj->DisplayDetails();
Use double underscores in __construct() and $this
to 'echoes' parameters on DisplayDetails
function DisplayDetails()
{
echo $this->custId, "<br>", $this->custName;
}
imho correct way is
class Customer
{
public $custId;
public $custName;
// double underscores
function __construct($custId = 'Eazy01', $custName = 'EazyLearnKallor')
{
$this->custId = $custId;
$this->custName = $custName;
}
function DisplayDetails()
{
echo $this->custId . '<br />' . $this->custName;
}
}
$obj = new Customer();
$obj->DisplayDetails();
There's not really a "correct" way, but that will work just fine. Usually, you pass the values to the constructor (note double underscore):
function __construct($id, $name)
{
$this->custId = $id;
$this->custName = $name;
}
Then:
$obj = new Customer('Eazy01', 'EazyLearnKaloor');
Also, when you refer to them, you need to prefix them with $this:
function DisplayDetails()
{
echo $this->custId . "<br>";
echo $this->custName;
}