Reputation: 4047
I made the following example class
class a{
function __construct(){
$a =10;
$b=9;
}
}
$z=new a();
I would like to know how can I access $a and $b using the object(or by other means) to perform a single $a + $b addition. I know this can be done using the super global array but I would like to know are there any other methods to do this rather than declaring them global.
I know the code doesn't make much sense but doing it for example purposes
Upvotes: 0
Views: 1685
Reputation: 9432
You can`t return in the cunstructor even if you do:
class a{
public $a;
public $b;
function __construct(){
$this->a =10;
$this->b=9;
return 19;
}
}
$b = new a();
var_dump($b);
You would get an instance of a, thus you heve the alternatives: make a new method:
<?php
function add()
{
return $this->a+$this->b;
}
?>
Or generate getter`s (for both) =>
<?php
function getA()
{
return $this->a;
}
?>
Or declare them public and access them:
$z->a+$z->b;
It depends on you`r app architecture or restrictions you might have or want to impose
Upvotes: 0
Reputation: 44844
By name constructors are used for any initialization that the object may need before it is used. So if you do the way you are doing
function __construct(){
$a =10;
$b=9;
}
The variables $a & $b scope are limited to the function __construct().
You may need $a & $b as class variable rather than the function something as
class a{
public $a;
public $b;
function __construct(){
$this->a =10;
$this->b=9;
}
}
$z=new a();
// access a & b as
$z->a ; $z->b
The constructor here will do the initialization job of the variables when you instantiate the object.
Upvotes: 1
Reputation: 1700
In your example there are two local variables in the function. You should create class fields to access them via object:
class a {
public $a;
public $b;
function __construct() {
$this->a = 10;
$this->b = 9;
}
}
$z = new a();
echo $z->a;
echo $z->b;
Upvotes: 0
Reputation: 24661
Make those variables properties instead:
class a
{
public $a;
public $b;
public function __construct() {
$this->a = 10;
$this->b = 9;
}
}
$z = new a();
echo $z->a;
Better yet though, abstract your operation into a function:
echo $z->addProperties();
// Inside a class
public function addProperties() {
return $this->a + $this->b;
}
Later on, when you want to add a third property that you need to add to your other two (or even subtract or multiply by), then all you have to do is change your a
class, and not any code that actually uses it.
Upvotes: 3