php Classes

To create an object with a specified class, use the new keyword, like this: object = new Class. Here are a couple of ways in which we could do this:

$object = new User;
$temp = new User('name', 'password');

On the first line, we simply assign an object to the User class. In the second, we pass parameters to the call.
A class may require or prohibit arguments; it may also allow arguments, but not require them.

Accessing Objects

Let’s add a few lines more to above example and check the results. below extends the previous code by setting object properties and calling a method.

class User {
	public $name, $password;
	function save_user() {
		echo "Save User code goes here";

$object = new User ();
print_r ( $object );
echo "<br />";
$object->name = "john";
$object->password = "123456";
print_r ( $object );
echo "<br />";
$object->save_user ();


User Object ( [name] => [password] => ) 
User Object ( [name] => john [password] => 123456 ) 
Save User code goes here

As you can see, the syntax for accessing an object’s property is $object->property. Likewise, you call a method like this: $object->method().

You should note that the example property and method do not have $ signs in front of them. If you were to preface them with $ signs, the code would not work, as it would try to reference the value inside a variable. For example, the expression $object->$property would attempt to look up the value assigned to a variable named $property (let’s say that value is the string “brown”) and then attempt to reference the property $object->brown. If $property is undefined, an attempt to reference $object->NULL would occur and cause an error.