$b=('some data from db')
class one{

public $a=$b;


i want to initialize the $a with a variable outside the class, but it is not working.
Please how can do this.
Thanks in advace
3 Years
Discussion Span
Last Post by diafol

The best way is it do this in the class One's constructor. Pass $b as an initialization variable. That said, cereal's approach is also fine, as long as the $a member variable remains public. If at sometime in the future you decide it should be private, then his approach will not work.


This depends entirely on what you're trying to do. You should aim to give your class variables (or properties) the lowest visibility possible (i.e. private, protected, public, in that order), but of course it depends if you're going to access those variables directly from outside the class. You could access them indirectly with getters and setters, so still maintaining private (or protected) visibility.

If you're not going to access them at all from outside the class, only to initialize them, then you're probably better off passing the data as a parameter, either in the constructor or in another class function (method).

class myClass
    private $a;

    public function __construct($initA)
        $this->a = $initA;

    public function getA()
        return $this->a;

$myc = new myClass('blurb');
echo $myc->getA(); //'blurb'

IN the snippet above, you cannot change the value of $a once initialized.

Whatever you do, DO NOT use a global variable - there are so many poor tutorials on OOP PHP that have these little monsters scurrying all over the place.

If you do mean to modify the value from outside after initializing, then you can do so as cereal suggests or as below:

public function setA($newA)
    $this->a = $newA;

What the 'setter' gives you is the opportunity to validate the data with an optional datatype check. Using a "public" class variable (property) allows the client to have carte blanche over the change. This could result in bad things happening down the line that depend upon the value of $a.

Edited by diafol

Votes + Comments
Good example.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.