Friday 15 December 2017

PHP use global variables in class/object

itemprop="text">





Possible
Duplicate:

href="https://stackoverflow.com/questions/2671928/workaround-for-basic-syntax-not-being-parsed">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 ?
:)



Answer




The right way would be to use a href="http://www.php.net/manual/en/language.oop5.decon.php"
rel="noreferrer">constructor - a method that will run when the object is
created.



When you define href="http://www.php.net/manual/en/language.oop5.properties.php"
rel="noreferrer">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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...