<?php
$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

Recommended Answers

All 3 Replies

Hi, try:

<?php

    class One{
        public $a;
    }

    $b = 'Hello';
    $test = new One;
    $test->a = $b;

    echo $test->a;

For more information read about the visibility of class properties:

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.

Member Avatar for diafol

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.

commented: Good example. +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.