PHP Classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
anthony88guy
Forum Contributor
Posts: 246
Joined: Thu Jan 20, 2005 8:22 pm

PHP Classes

Post 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...
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: PHP Classes

Post 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?
anthony88guy
Forum Contributor
Posts: 246
Joined: Thu Jan 20, 2005 8:22 pm

Post by anthony88guy »

Yep, Thanks.

PHP 4.4.1
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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. :D
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: PHP Classes

Post 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).
(#10850)
Post Reply