Page 1 of 1
PHP Classes
Posted: Fri Jul 21, 2006 8:27 pm
by anthony88guy
I'm trying to teach myself classes in PHP from the
manual.
Here is my test class, which I'm having trouble with...
Code: Select all
<?php
class main
{
function hello($name)
{
var $nick; //line 6
$this->nick = $name;
echo 'Hello ' . $nick;
}
}
$main = new main;
$main->hello('ambrose');
?>
Parse error: parse error, unexpected T_VAR in /home/*/public_html/test.php on line 6
No clue what I'm doing wrong... Thanks...
Re: PHP Classes
Posted: Fri Jul 21, 2006 8:27 pm
by Luke
anthony88guy wrote:I'm trying to teach myself classes in PHP from the
manual.
Here is my test class, which I'm having trouble with...
Code: Select all
<?php
class main
{
var $nick; //line 6
function hello($name)
{
$this->nick = $name;
echo 'Hello ' . $this->nick;
}
}
$main = new main;
$main->hello('ambrose');
?>
Parse error: parse error, unexpected T_VAR in /home/*/public_html/test.php on line 6
No clue what I'm doing wrong... Thanks...
That should fix it...
What version of PHP are you using?
Posted: Fri Jul 21, 2006 8:31 pm
by anthony88guy
Yep, Thanks.
PHP 4.4.1
Posted: Fri Jul 21, 2006 8:35 pm
by Luke
Oh... well I gotta tell you.. I was having a hard time grasping the concept of classes and really understanding exactly what their purpose is until I started using PHP5's public and private keywords and researching php design patterns... once you get the basics down, research that stuff.

Re: PHP Classes
Posted: Fri Jul 21, 2006 8:49 pm
by Christopher
More OOPy would be to create an initialized object and then to tell it to do things -- like say hello.
Code: Select all
<?php
class Main
{
var $nick;
function Main($name)
{
$this->nick = $name;
}
function hello()
{
echo 'Hello ' . $this->nick;
}
}
$main = new Main('ambrose');
$main->hello();
?>
In PHP4 the name of the function called when an object is created (called the Constructor) is the same name as the class. In PHP5 it is called __construct() (but the PHP4 name also works).