-3
<?php

class foo
{
    public $a;

    public function __construct()
    {
        $a='value';
    }

}

$class = new foo();
echo $class->$a;

?>

I want to use the value $a in other parts of my script.

How do I retrieve a variable set in a php object and use it for other things outside of the object?

seamus
  • 2,229
  • 6
  • 24
  • 40
  • 1
    Tons of good advice/examples on the PHP documentation: http://php.net/manual/en/language.oop5.php – Jasper Aug 02 '13 at 16:31

3 Answers3

2

To set the value inside a method, the syntax is:

$this->a = 'value';

To obtain the value of the property from an instance of the class, the syntax is:

$foo = new foo();
echo $foo->a;

The Properties manual page goes into more detail.

rid
  • 57,636
  • 30
  • 143
  • 185
2

I'd recommend using a getter (see):

Inside your class.

private $a;

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

Outside your class.

$class = new foo();
echo $class->getA();

Important: Inside your class you should refer to $a as $this->a.

Community
  • 1
  • 1
federico-t
  • 11,595
  • 17
  • 64
  • 109
1

Use $this variable to assign and reference instance variables and functions on the current object.

In your case replace $a = 'value'; with $this->a = 'value';

vee
  • 37,584
  • 7
  • 71
  • 74