I am trying to further my understanding of classes and how to access variables within methods.

Is it possible to use a variable defined in a method without activating the method it is contained within.

For example in the code below I want to just print the value of the variable $this->a but not perform the method (ie not have '$a + mon' printed out)

<?php
class testclass{
var $a;

function atest(){
$this->a= "si";
echo $this->a."mon";
}

}

$object1 = new testclass;
$object1->atest();
?>

This prints 'simon' but how would I print the value of $a without activating the echo $this->a."mon"; line.

Do I need to put this second line in its own function?

    You can call it directly like so

    $object->a
    

    Since it has been defined. However it will also depend on when it is called. If you call it once the class has been initiated it will not have any value. However if its called after atest() it will have the value of "si"

      Ok thanks.. I think you have answered my question as you mention that atest() must be called in ordered for $this->a to have a value of "si" -- in doing so the atest() method will be activated and the "simon" value printed out.

        <?php 
        class testclass{ 
        var $a; 
        
        function atest(){ 
          echo $this->a."mon"; 
        } 
        
        function testclass() {
          $this->a = 'si';
        }
        
        } 
        
        $object1 = new testclass(); 
        echo $object1->a; 
        
        ?> 
        

        the testclass() method is the constructor, and it will be called whenever you instantiate the class ($object1 = new testclass())

        The constructor is useful for setting values/calling functions needed to initialize the class.

        hope this helps you

          Write a Reply...