0

For example, let's say I have the file "other.php" that contains this code

class Building
{
    public $name;

    function __construct($name)
    {
        $this->$name = $name;
    }
}

$bd = new Building("Name");
echo $bd->$name;

This returns errors like this:

Notice: Undefined variable: name in (...)
Fatal error: Cannot access empty property in (...)

And I wish for an output like

Name

How do I access PHP object properties in such a fashion? Thank you.

0

3 Answers 3

3

Get rid of the second $. You access it with $bd->name;. Same goes for inside the class. Put $this->name instead of $this->$name in there.

Generally, just don't put a $ after the -> operator.

Look at the PHP Documentation for reference.

Sign up to request clarification or add additional context in comments.

6 Comments

Doing that seems to remove the error but gives me no output. This is my specific code.
Same goes for inside the class. You access it with $this->$name, while it should actually be $this->name.
When I include that file in my index.php using <?php include("buildings.php"); ?> and then later on in my index.php write <?php echo $buildings_HSB->name; ?> it gives errors. Notice: Undefined variable: buildings_HSB in (...) and Notice: Trying to get property of non-object in (...)
And in another HTML file I am doing <?php include("buildings.php"); ?> and then <?php echo $buildings_HSB->name; ?> and am receiving the errors listed above.
|
1

Avoid the $ sign infront of name.

It should be like echo $bd->name;..

Comments

1

First fix your class code:

function __construct($name)
{
    $this->$name = $name;
}

Should be this:

function __construct($name)
{
    $this->name = $name;
}

Which will allow you to access it like this:

$bd = new Building("Name");
echo $bd->name;

Addressing your issue in this comment

You get that error because you havent instantiated that variable.

You should do this:

$buildings_HSB = new Building("Name");
echo $buildings_HSB->name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.