Jump to content

Getters and Setters in PHP


tab4trouble

Recommended Posts

I'm having issues with getter and setter functions in PHP. Following is how I have written my PHP classes.

--------------------------------------------------------------------------------------------------------------------

File1.php

--------------------------------------------------------------------------------------------------------------------

<?php
class TestClass1 {
    private $var;
     public function get_varvalue() {
        return $this->var;
    }

    public function set_varvalue($TestVar) {
        $this->var = $TestVar;
    }    
}
?>

 

 

--------------------------------------------------------------------------------------------------------------------

File2.php

--------------------------------------------------------------------------------------------------------------------

<?php
$obj = new TestClass1();
$obj->set_varvalue("someText");
?>

 

 

--------------------------------------------------------------------------------------------------------------------

File3.php

--------------------------------------------------------------------------------------------------------------------

<?php
class TestClass2 {
   $obj2 = new TestClass1();
   echo $obj2->get_varvalue();
}
?>

 

File1, File2 and File 3 are separate PHP files. File2 uses the TestClass1 object to set the value to variable 'var' but when I try to get the value print the value in File3.php by creating an object for the same class and calling the get_varvalue() function, I'm getting a blank output.

 

Please help me to solve this issue.

 

Thank you.

Regards,

tab4trouble

Link to comment
https://forums.phpfreaks.com/topic/236397-getters-and-setters-in-php/
Share on other sites

Why don't you make a real getter instead of one for a specific variable, so you could access all class properties from one method?

class whatever
{
            protected $_stuff1 = 'stuff 1';
            protected $_stuff2 = 'stuff 2';

           public function get($key)
           { 
                  return $this->$key;
            }

           public function set($key, $value)
           {
                  $this->$key = $value;
                  return $this;
            }
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.