Reputation: 21
How I can use a variable in another variable in a php class like this:
<?php
class example
{
var $first_num = 8;
var $second_num = $first_num + 3;
public function forexample($num)
{
if($num == $this->first_num)
{
echo $this->second_num;
}
}
etc...
}
?>
I want use this way in a class. please help me.
Upvotes: 0
Views: 94
Reputation: 2548
You have to utilize the constructor. Once you do that, you can use the variables anywhere in the class!
<?php
class example {
private $first_num;
private $second_num;
function __construct() {
$this->first_num = 8;
$this->second_num = $this->first_num + 3;
}
}
?>
Since you updated your question, you will have to set your variables to public not private.
Upvotes: 0
Reputation: 42969
What you want to do is actually this:
<?php
class example
{
var $first_num;
var $second_num;
function __construct() {
$this->first_num = 8;
$this->second_num = $this->first_num + 3;
}
}
Remember that while you can initialize variables directly while declarating them in the class body, you might want to use the class constructor for more complicated initializations.
In this specific case, it is forbidden to declare a variable using a non-constant value, so the use of the constructor is mandatory for the variable $second_num
.
Also, if you want to fine-tune variable visibility, you might want to use the private
, public
, or protected
access modifiers instead of the legacy var
, which is deprecated.
Upvotes: 1
Reputation: 4239
You will have to do this in the constructor. See http://php.net/manual/en/language.oop5.properties.php :
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
See SirDarius's answer.
Upvotes: 0