p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: Classes and Functions


Message #1 by Empier4552@a... on Tue, 29 Oct 2002 17:32:01 EST
Hey right now im building a class with functions inside. However several 
variables i declared and then gave values to in the class (not in any 
function) but i get errors when they were made. I tried several ways as shown 
below anyone know the problem and solution?

Below gives me the following error: Parse error: parse error, expecting 
`T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in 
/u/htdocs/empier/traders/editor.php4 on line 16

class editor {
var $db_name;
var $connection;
var $db;
var $result;

$this->db_name = "dbname";
$this->connection = @mysql_connect("localhost", "user", "pw") or die("Unable 
to Connect.");
$this->db = @mysql_select_db($db_name, $connection) or die("Couldn't find 
database");
$this->result = @mysql_query($sql,$connection) or die("Couldn't Execute");

function edit_company() {
$this->db_name;
$this->connection;

}

}

I also tried instead of $this->db_name="dbname" 
$db_name="dbname";

I still got the parse error. Can anyone clue me in on this as im new to 
classes and functions?

Message #2 by "Nikolai Devereaux" <yomama@u...> on Tue, 29 Oct 2002 14:47:44 -0800
You can't set variables outside of a function definition because they require
an instance of the class to be created.  If you don't have an object created of
that class type, then memory has not yet been allocated for its member
variables.

In other words, there is no $this.

Read the manual section at:
  http://www.php.net/oop


The answer to your problem is to assign the values of your variables in the
object constructor.  The object constructor is a function inside a class
definition with the same name as the class.


class editor
{
  var $db_name;
  var $connection;
  var $db;
  var $result;

  function editor()
  {
    $this->db_name = "dbname";
    $this->connection = @mysql_connect("localhost", "user", "pw")
             or die("Unable to Connect.");
    $this->db = @mysql_select_db($db_name, $connection)
             or die("Couldn't find database");
    $this->result = @mysql_query($sql,$connection)
             or die("Couldn't Execute");
  }
};


Keep in mind that $sql is never defined...


take care,

nik


  Return to Index