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
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;
            }
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.