Pass var from one class to extended class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ziycon
    Contributor
    • Sep 2008
    • 384

    #1

    Pass var from one class to extended class

    I need to pass a var from the parent class to an extend class but need it to keep the value that was set during the running of the main class. the code i have so far is below but isn't keeping the value from the parent class.

    The problem is getting the 'v1' value passed to the ext class to use it in a SQL query. Any ideas??

    Code:
    class main {
       var $v1;
    
       function __consturct() {
       }
    
       function someFunc() {
          ..do stuff..
    
          $v2 = &new ext($this->v1);
    
          ..do stuff..
       }
    }
    class ext extends main {
       ..do stuff..
       ..get v1 value from parent class..
       ..use v1 value in SQL query and insert values returned..
    }
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    It's there.

    $v1 doesn't have a value though.

    Here is a little example.
    Code:
    <?php
    	class main {
    	   var $v1= "test";
    	 
    	   function __consturct() {
    	   }
    	 
    	   function someFunc() {
    
    		  $v2 = &new ext($this->v1);
    	   }
    	}
    	class ext extends main {
    		function showVar ()
    		{
    			return $this->v1;
    		}
    	}
    
    
    	$myExt = new ext();
    	echo $myExt->showVar();
    	echo "<br />" . $myExt->v1;
    ?>

    Comment

    • ziycon
      Contributor
      • Sep 2008
      • 384

      #3
      I meant to say that $v1 does have a value set in the parent class that needs to be passed to the extend class, is there a way to do this?
      Code:
      class main {
         var $v1;
      
         function __consturct() {
         }
      
         function someFunc() {
            ..do stuff..
      
            $this->v1 = "string";
      
            $v2 = &new ext($this->v1);
      
            ..do stuff..
         }
      }
      class ext extends main {
         ..do stuff..
         ..get v1 value from parent class..
         ..use v1 value in SQL query and insert values returned..
      }

      Comment

      • JKing
        Recognized Expert Top Contributor
        • Jun 2007
        • 1206

        #4
        Did you try my example?

        Line 16 shows you how to access the variable. It is important that the parent class' constructor is called before inherited variables can be accessed.

        Comment

        Working...