Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2006
    Posts
    96
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Joining variables in a class

    Hi all
    First off l best mention that classes are new to me and to be honest I'm a bit intimidate by the whole thing. Any way as a way to break myself into things (gently) I've been having a play at creating a class that will generate a sting from certain variables. You'll see what I mean from the code (that doesn't work!)

    Code:
    class xtags {
    	
    	var $coord_x = 0;
    	var $coord_y = 0;
    	var $xtag;
    	
    	 function create_tag() {
    	
    		$this->$xtag =  $this->$coord_x . ',' . $this->$coord_y;
    		
    		return $this->$xtag;
    		
    		}
    }
    
    
    $test = new xtags();
    $test->coord_x = 1;
    $test_tag = $test->create_tag();
    
    echo $test_tag;

    Basically I need to generate a string that has two coordinates separated by a comma. 1,0 but what I get is ,

    While you'll be right in saying the example doesn't justify being a class ultimately I'll want to set say 50 variables joined into a string but may only need to change one. Yes it could be done in a standard way but this is just to help me understanding the workings of a class.

    Obviously it's this:
    $this->$xtag = $this->$coord_x . ',' . $this->$coord_y;
    that's not producing the result so how do you join the variables?

    Cheers

  • #2
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    You have way too many $ in there. The syntax is class::$static_variable and $instance->instance_variable, so
    PHP Code:
    $this->$xtag =  $this->$coord_x ',' $this->$coord_y;
    return 
    $this->$xtag
    really should be
    PHP Code:
    $this->xtag =  $this->coord_x ',' $this->coord_y;
    return 
    $this->xtag

  • #3
    New Coder
    Join Date
    Jul 2006
    Posts
    96
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Many thanks.

    So basically $this-> omits the need for $ as '$this->stringname' is simply refering to the '$stringname' of the current object.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •