Home » Php » oop – Calling a variable from another class PHP

oop – Calling a variable from another class PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m in the phase of learning OOP in PHP and i wanna know how to call a variable from another PHP class.

eg.

class first {
    public $var1 = 1;
}

I guess it’s this way but i don’t know how to continue:

$first = new $first();

How to&Answers:

You should do something like this:

$first = new first();
echo $first->var1;

Answer:

You need to call it like this:

$first = new first();
$first->var1;

Answer:

For better way make like 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 may try handling some exceptions.

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

Answer:

You will need to create an instance of the class:

$instance=new first();

and then you can access the variable from that instance:

$var=$instance->var1;

Note – there is no $ before the class name when you create an instance of it.

Answer:

<?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";
?>