PHP Index

What is $this

The object $this is used when you are coding inside of a class. When you are outside of a class and you create a new instance of an object, you would use whatever variable name you choose.

Here's an example.

<?php
class my_new_class {
     $this->name = "Joe";
     $this->phone = "555-5555";
}
?>

The above example shows how to use $this. Basically the -> just says that name and phone are variables.

To call those variables outside of the class you would do this.

$a_var_to_create_object = new my_new_class();

print("The name is " . $a_var_to_create_object->name);

print("The phone# is " . $a_var_to_create_object->phone);

The benefit here is that you can always use the variable name name and phone, you just create a new instance of the class object and reference name and phone from whatever variable name you give the new instance. In the example above, I chose $a_var_to_create_object.

You can also use arrays, here is an example.

<?php
class my_new_class {
     $this->info['name'] = "Joe";
     $this->info['phone'] = "555-5555";
}

$new_obj = new my_new_class();

print("This is the name " . $new_obj->info['name'] . " and this is the phone number " . $new_obj->info['phone'] . ".");
?>

Sorry if my terminology is a bit off.

Another simple class example

Below are a few very simple examples of using classes.

<?php
class math_class {
  function add_me($a,$b){
    return $a + $b;
  }
}

$add_me = new math_class();

print $add_me->add_me(2,5);
?>

Here's another way to add two numbers together.

class my_math {
  function add_two_numbers($a,$b){
    $this->a = $a;
    $this->b = $b;

    return $a + $b;
  }
}

$office = new my_math();
print($office->add_two_numbers(2,5));

This one just takes an email address and stores the username (part before @) into the variable $this->email which can be called outside of the class as $what_ever_object->email. The $what_ever_object in the example below is $mydep, and that's your choice. This is why classes are useful -- you get to keep the variable email so that you don't have to have an email variable for every employee that get's processed. You just create a new object, and all the variables inside that class remain the same. I've read that PHP isn't an object oriented programming language and that classes actually slow down performance. I've also read that you can program perfectly with or without classes and accomplish the same goal.

class employee {
  var $email;

  function empEmail($email){
    $e_arr=explode("@", $email);
    $this->email = trim($e_arr[0]);
  }
}
# <!--end:class:employee-->

$mydep = new employee();
$mydep->empEmail('username@domain.com');

print($mydep->email);

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.