PHP Fatal error: Can't use method return value in write context

Discussion in 'PHP' started by lektrikpuke, Dec 2, 2012.

  1. #1
    I receive an error message if I uncomment the commented line below. What am I doing wrong?
    
    <?php
    class tClass{
    	private $var1;
    	private $var2;
    	
    	public function __construct($v1, $v2){
    		$this->setVars($v1, $v2);
    	}
    	
    	public function setVars($v1, $v2){
    		$this->var1 = $v1;
    		$this->var2 = $v2;
    	}
    	
    	public function getVars($var){
    		return $this->$var;
    	}
    }
    
    $eMsg = '';
    $inTClass = new tClass('a', 'b');
    
    function testError($postArray = array()){
    	foreach($postArray as $post){
    		//$inTClass->$setVars($post) = trim($_POST[$post]);
    		// uncomment above and get error -  PHP Fatal error:  Can't use method return value in write context
    		$tempArray[$post] = trim($_POST[$post]);
    	}
    	echo "<pre>\n";
    	print_r($tempArray);
    	echo "</pre>\n";
    }
    
    if(isset($_POST['submit'])){
    	$varArray = array("var1", "var2");
    	$eMsg .= testError($varArray);
    }
    ?>
    <form method='POST' name='frmOne'>
    	<p>
    	</p>
    	<span class="fieldlabel">Test Form: </span>
    	<input type="text" name="var1" value="<?php echo $inTClass->getVars('var1'); ?>" />
        <input type="text" name="var2" value="<?php echo $inTClass->getVars('var2'); ?>" />
    	<p>
            <input class='buttons' type='submit' name='submit' value='Save' />
            <input class='buttons' type='reset' value='Reset' />
        </p>
    </form>
    
    PHP:

     
    Last edited: Dec 2, 2012
    lektrikpuke, Dec 2, 2012 IP
  2. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #2
    $post is read-only.
     
    Rukbat, Dec 2, 2012 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    Shouldn't this:
    $inTClass->$setVars($post)

    Be:
    $inTClass->setVars($post)

    Also, the setVars method requires 2 arguments and you're only passing it 1. Lastly, you're trying to call a method and assign a value to it (setVars($post) = trim($_POST[$post])), which makes no sense at all. What you're trying to accomplish here?
     
    jestep, Dec 3, 2012 IP
  4. lektrikpuke

    lektrikpuke Well-Known Member

    Messages:
    297
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    113
    #4
    The code was stripped out of something else, and I rewrote it be much more compact (removing most of the unnecessary stuff). Thought I did a good job till I read your comments. The $setVars issue with regard to $, just didn't see that till you pointed it out. Same goes for the passing in one param where two are required. Thanks.
     
    lektrikpuke, Dec 3, 2012 IP