(click anywhere to close)
OPEN MENU

[PHP] Objects I

category: Website | course: PHP | difficulty:

Finally, finally, finally we arrive at the big guns. The whole course has been building up to this moment, and now we can use all our knowledge to start performing some object magic.

I’ve briefly mentioned them a few times already, especially in relation with arrays and loops, but what are objects? Objects are, essentially, an intuitive and easy way of programming. Instead of using a lot of separate functions, we can group together related information inside one object – just as in the real world. If you want work with multiple blog posts (with lots of metadata attached to them), turn every blog post into a single object. If you want to create collectible items for a browser game, turn every item into an object.

What’s the difference with arrays? For starters, objects can store key-value pairs as well as functions. Additionally, objects can inherit from or extend other objects – so, for example, you could use one “master object” to hold all the data that all objects will have in common.

PHPObjectsClasses

Classes

Remember this: an object is a single, specific instance of a certain class. Within PHP, you must first define a class, and once that's done you can instance as many objects of that class as you want. Think of classes as blueprints for objects – within them you can define what you want a certain class of objects to look like, but nothing is actually created until you create a new object of that type.

To create a new class, use

class SomeClass { code }
class User {
	//code that provides all sorts of information about this User
}

It’s a custom to write classes with capital letters starting each word. This is to make sure you can easily see the difference between creating an object and calling a function later on.

Classes follow the same naming rules as variables.

Creating Objects

To create a new object from an already defined class, use the new keyword:

$var = new SomeClass();

I think the fact that you need to use the new word is a good reminder of how objects work; every object you create is unique, even though it shares the same class with other objects. Two cars might be exactly the same, but it’s still two separate cars.

class User {
	//code that provides all sorts of information about this User
}

//$user_1 and $user_2 are two seperate objects, instantiated from the same class
$user_1 = new User();
$user_2 = new User();

Defining Properties & Methods

As I said, objects can contain key-value pairs and functions. In the case of objects, we call them properties and methods instead. (This is to differentiate it from regular variables and functions.)

To create a property, one simply defines a variable within the class definition. It’s important to note, though, that you can only assign values to the variable – expressions are not allowed. To create a method, one simply defines a function within the class definition.

PHP, however, requires you to say something about the visibility of the properties and methods. For safety reasons, we sometimes don’t want other parts of the code lurking around in our properties. We have three keywords for that:

  • public: the property/method is accessible from anywhere
  • protected: the property/method is accessible only from within the class itself and inherited classes
  • private: the property/method is accessible only from within the class itself
/* The user has three properties (username, favrite pet, and password)
   The user has one method (that prints a message) */
class User {
	public $username = "Ginty";
	public $favorite_pet = "Rabbits";
	private $password = "gintyisawesomeyeah";

	public function print_message() {
		echo "Hey there, I am Ginty!";
	}
}

You can also define constants with the familiar const keyword. These are automatically public and need no visibility keyword in front of them.

Accessing Properties & Methods

To access a property or method, we use the arrow syntax ( -> ):

$some_object->property; $some_object->method();
class User {
	public $username = "Ginty";
	public $favorite_pet = "Rabbits";
	private $password = "gintyisawesomeyeah";

	public function print_message() {
		echo "Hey there, I am Ginty!";
	}
}

$user = new User();
echo $user->username; //Prints: Ginty
echo $user->password; //Prints: ERROR cannot access private property 

$user->print_message(); //Prints: Hey there, I am Ginty!

Leave out the dollar sign when accessing a property. If you do include the dollar sign, PHP will use the value of that variable to access a property.

The $this Pseudo-variable

The arrow syntax I just introduced isn’t just for accessing properties/methods from outside of the object – it’s also the only way to access one from within the object. However, how do we access the current object from within the class definition? I mean, is there any way we could access the current object that we’re in? Well, we can do so using the $this pseudo-variable!

This variable can be used in a class definition to reference the current object, and therefore allows us to access its own properties and methods. You’re going to need it a lot.

class User {
	public $username = "Juan";
	public $favorite_pet = "Rabbits";
	private $password = "juanisawesomeyeah";

	//Returns true only if $password and $pwd match
	public function check_password($pwd) {
		return ($this->password === $pwd) ? true : false;
	}

	public function print_message() {
		echo "Hey, I am $this->username, and I like $this->favorite_pet.";
	}
}

$user = new User();

$is_password_correct = $user->check_password("juanisawesomeyeah"); //Returns true

$user->print_message(); //Prints: Hey I am Juan, and I like rabbits.

/* As you can see, we can't access the password directly, but we can check if the password we entered is correct (which is more secure than if anyone were to just get the password) */

I call it a pseudo-variable, as it is a variable – but we can’t change it ourselves. It automatically adapts itself to the object in which we’re currently executing a function.

Object Operators

Because objects are so complex, they only allow two operators:

Operator

Description

==

Returns true if both objects have the same properties/methods and values, and are instances of the same class.

===

Returns true if both objects refer to the exact same instance of the same class.

How the second (strict) operator works has everything to do with how objects are assigned and copied, which next section is about.

class User {
	public $username = "Juan";
	public $favorite_pet = "Tree Kangaroos";
}

$user_1 = new User();
$user_2 = new User();

var_dump($user_1 == $user_2);  //Prints: bool(true)
var_dump($user_1 === $user_2); //Prints: bool(false)

Object Assignment

With all the other data types, if you assign one variable to another, the value is simply copied. If you wanted to avoid that, you could use a reference to make two variables identical.

With objects, it works a little differently. If you assign a variable containing an object to a new variable, an address pointing to the object is passed on. This means that both variables will point to the same object and both will edit the same object. But, it’s not a reference, as changing one variable will not automatically update the other. So, it’s a middle-ground between copying and referencing.

class User {
	public $username = "Juan";
	public $favorite_pet = "Tree Kangaroos";
}

$user_1 = new User();
$user_2 = $user_1;

$user_2->username = "HE WHO MUST NOT BE NAMED";

//Both $user_1 and $user_2 are now exactly the same object
var_dump($user_1);
var_dump($user_2);
/* Both print
	object(User)#1 (2) {
	  ["username"]=>
	  	string(24) "HE WHO MUST NOT BE NAMED"
	  ["favorite_pet"]=>
	  	string(14) "Tree Kangaroos"
	}
*/

$user_2 = 0;

//Now $user_1 will contain the original object, but $user_2 is 0. If it were a reference, $user_1 and $user_2 should both have been 0 by now. But objects are not passed by reference.

But, what do I do if I actually want to copy the object? Well, because objects are supposed to be unique, we call it cloning. To do so, use

$var = clone $obj;
class User {
	public $username = "Juan";
	public $favorite_pet = "Tree Kangaroos";
}

$user_1 = new User();
$user_2 = clone $user_1;

var_dump($user_1);
var_dump($user_2);
/* Prints
	object(User)#1 (2) {
	  ["username"]=>
	  	string(4) "Juan"
	  ["favorite_pet"]=>
	  	string(14) "Tree Kangaroos"
	}
	
	object(User)#2 (2) {
	  ["username"]=>
	  	string(4) "Juan"
	  ["favorite_pet"]=>
	  	string(14) "Tree Kangaroos"
	}
*/

Object Iteration

We’ve already seen (in the Loops chapter) that you must use the foreach loop to iterate through all the properties and methods of an object. But, there’s a subtle difference to be aware of – it will only loop through all the visible elements.

So, if the loop is somewhere outside of the class, it will only go through all the public properties. But, if it’s inside the class definition, it will go through all properties.

class User {
	public $username = "Juan";
	public $favorite_pet = "Tree Kangaroos";
	private $password = "treesareawesomeyeah";

	public function iterate() {
		foreach($this as $value) {
			echo $value . " | ";
		}
	}
}

$user = new User();

//This prints: Juan | Tree Kangaroos |
foreach($user as $value) {
	echo $value . " | ";
}

//This prints: Juan | Tree Kangaroos | treesareawesomeyeah |
$user->iterate();
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)