Page 1 of 1

Class returing Cannot re-assign $this

Posted: Sun Jun 08, 2008 6:05 pm
by tecktalkcm0391
I am writing one of my first classes... or at least attempting...

I am trying to achieve the same thing in the class as below:

Code: Select all

function connect($dbc_name = $default){
    ...
}
This is what I have:

Code: Select all

<?php
class db {
    private $db_host = '.com';
    private $db_user = 'sandboxuser';
    private $db_pass = 'sandbox';
    private $db_name = 'sandbox';
    private $dbc_name;
 
    function connect($this->dbc_name = $this->db_host){
        $this->connectionLink = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        if($this->connectionLink){
            mysql_select_db($this->db_name, $this->connectionLink);
        }
    }
    
}
 
$test = new db();
$test->connect();
 
 
?>
I just can't get the code to work without returing "Fatal error: Cannot re-assign $this ..."

Re: Class returing Cannot re-assign $this

Posted: Sun Jun 08, 2008 6:24 pm
by VladSun
You can't use $this as function parameter in the function definition. You need somtehing like this:

Code: Select all

function connect($db_host){
        $this->db_host = $db_host;
        $this->connectionLink = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        if($this->connectionLink){
            mysql_select_db($this->db_name, $this->connectionLink);
        }
    }

Re: Class returing Cannot re-assign $this

Posted: Sun Jun 08, 2008 7:22 pm
by tecktalkcm0391
Would this be the same as:

Code: Select all

<?php 
function connect($dbname = 'test'){
...
}
?>
Where if you do connect() the $dbname would be test and if you do connect('database') the $dbname would be 'database'

Re: Class returing Cannot re-assign $this

Posted: Fri Jun 13, 2008 7:47 pm
by tecktalkcm0391
I still can't get this working. Any ideas please!!

Re: Class returing Cannot re-assign $this

Posted: Fri Jun 13, 2008 8:56 pm
by hansford
I agree with vladsun. Also, declare connectionLink; in the class but don't assign a value. you're getting errors b/c you're trying to assign values in the function(args) pass the args and do the assigning inside the function.

Re: Class returing Cannot re-assign $this

Posted: Fri Jun 13, 2008 9:04 pm
by Christopher
Typically I use a null default value when I want something like this:

Code: Select all

class db {
    private $db_host = '.com';
    private $db_user = 'sandboxuser';
    private $db_pass = 'sandbox';
    private $db_name = 'sandbox';
 
    function connect($db_name=null){
        if ($db_name !== null) {
            $this->db_name = $db_name;
        }
        $this->connectionLink = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        if($this->connectionLink){
            mysql_select_db($this->db_name, $this->connectionLink);
        }
    }