Possible Duplicate:
Workaround for basic syntax not being parsed
I don't understand how to use variables inside objects in php.
For example in javascript I would do this and it would be fine.
var foo = 10,
bar = {option: foo+5}
;
console.log(bar.option);
in php I do the same but it fails
$variable = 10;
class myObject {
var $username = $variable + 5 ;
var $zzz = $username + 5;
}
Also is it possible to use $this in object or only in functions ?
And lastly how would I set up variable based on another inside the same object like in second line of myObject ? :)
The right way would be to use a constructor - a method that will run when the object is created.
When you define class properties, you can only use constant values (1, 'xyz', array() are fine for example), not expressions that need to be evaluated at runtime.
Pass the variable to the constructor, and don't use global variables.
class myObject {
public $username;
public $zzz;
public function __construct($variable) {
$this->username = $variable + 5 ;
$this->zzz = $this->username + 5;
}
}
$obj = new myObject(10);
echo $obj->username; //15
In PHP, you don't need to use classes and objects if you don't want to write OOP code. You can simply create good old functions. But if you want to use them, try to get familiar with OOP concepts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With