0

I got this line of code: $user->create_account($username, $password);. What it does is taking username and password and create a new user, but my question isn't exactly about that. If I was calling a function, I would have done only:

create_account($username, $password);

so what does the "->" means? Is that actually a function?

Forgive me for the dumb question, but i have never seen something like that in an year of php. If it was Jquery it would have been ok but it's not.

user1620696
  • 9,035
  • 12
  • 42
  • 76
Giacomo Tecya Pigani
  • 2,027
  • 22
  • 33

5 Answers5

3

In this case $user is an instance of a class (an object) that has a method called create_account defined. So you're calling the create_account method on the $user object.

Example:

class User {
    function create_account($username, $password) {
        // Create the account
    }
}

$user = new User();
$user->create_account($username, $password);

This is a quick example of how the User class could be implemented.

Hein Andre Grønnestad
  • 6,438
  • 2
  • 28
  • 41
2

The -> means that you are calling a method from an object. One object is just one instance of a class and a class is just a definition of a type. Classes are the fundamental building blocks of Object Oriented Programming. When you create a class you are abstracting a concept: defining what some concept is in your application.

This definition contains both behaviors and properties. For instance, when you create a class user, one possible behavior of users is to create a new account and one possible property is the username.

In PHP behaviors are implemented as functions inside objects. Just to make distinction clear from functions outside objects we call those special functions methods. So when you define a class user inside of it you create a function create_account which represents the behavior of the user in creating one account in the system.

When you have a class User in php you create objects of this class (variables of type User) by the following syntax $user = new User(); and some parameters can be passed to construct the object (read about constructors). Then, having the object $user you can access its behaviors and properties by the -> syntax.

In that case, $user->create_account($username, $password) calls the method create_account of the User type passing the right parameters.

user1620696
  • 9,035
  • 12
  • 42
  • 76
1

Ever heard of Object Oriented Programming? $user is an object, and create_account() a method (=function) of this object.

Pascal Le Merrer
  • 5,177
  • 17
  • 32
1

means "create_account" function belong to $user object from class you created

1

create_account is a function, but it would be more proper to call it a method. $user is an object with method create_account. -> is the accessor operator within PHP. It is used to access an object's public methods and properties. See http://www.php.net/manual/en/language.oop5.php.

Daniel Farrell
  • 8,759
  • 1
  • 21
  • 21