Calling a variable from another PHP class

I am in the process of learning OOP in PHP and I want to know how to call a variable from another PHP class.

eg.

class first { public $var1 = 1; } 

I suppose so, but I don't know how to proceed:

$ first = new $ first ();

+7
source share
5 answers

You should do something like this:

 $first = new first(); echo $first->var1; 
+14
source

You need to call it like this:

 $first = new first(); $first->var1; 
+2
source

For a better way to do this:

 class first { private $var1 = 1; function getVar(){ return $this->var1; } function setVar($value){ $this->var1 = $value; } } 

Or like this:

 class first { private $var1 = 1; function __get(){ return $this->var1; } function __set($key,$value){ $this->$key = $value; } } 

In this case, you can try some exceptions.

Manually: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

+1
source

You will need to create an instance of the class:

 $instance=new first(); 

and then you can access the variable from this instance:

 $var=$instance->var1; 

Note. When you instantiate this object, there is no $ in front of the class name.

0
source
 <?php class Myname { public static $name='Your First Name'; } class Mylast { public static $last='Your Last Name'; } class Fullname { public static function staticValue() { return Myname::$name."--".Mylast::$last; } } print Fullname::staticValue() . "\n"; ?> 
0
source

All Articles