Accessing PHP objects’ methods and properties

A couple of participants in Boston PHP‘s self-study PHP Percolate, Jim Wright and Jared Stenquist, are confused about the use of the -> operator, which is introduced on page 44 of PHP Solutions, 2nd Edition. Since others might be in a similar situation, I decided to write a blog post about it.

Although PHP isn’t an object-oriented language, it has extensive support for objects. Also, since PHP 5, many core aspects of the language use objects rather than ordinary (procedural) functions. An object is a special data type that is capable of storing and manipulating values. You create an object from a class, which is a collection of functions and variables that define the object’s characteristics. Some classes, such as DateTime and Mysqli, are predefined by PHP, but you can also define your own.

The advantage of using classes and objects is that, once the class has been defined, they reduce the amount of code you need to write. An object inherits all the functions and variables defined by the class. That’s not all. Each object is independent, so you can create several objects from the same class to store different values, but they all share the same functions. Up to now, I’ve referred to functions and variables, but when talking about objects and classes, a function is called a method, and a variable is called a property. Whenever you want to use an object’s method or property, you need to use the -> operator.

You create an object by calling the class’s constructor method (which has the same name as the class) with the new keyword. Most constructor methods also accept arguments that set the initial properties of the object. In the case of the built-in DateTime class, you can use a string to specify the date. Without any arguments, it creates an object for the current date and time. For example, the following code creates two objects, one for today, and the other for Christmas Day 2011:

$today = new DateTime();
$xmas2011 = new DateTime('12/25/2011');

The $today object now contains the current date and time, but $xmas2011 contains the date for December 25, 2011 (because the time wasn’t specified when creating the object, it’s set to midnight at the start of the day).

To display the day of the week, you need to use the DateTime class’s format() method, and pass it a format string (they’re listed in Table 14-4 on page 402 of PHP Solutions, 2nd Edition) for the weekday name like this:

echo $today->format('l');

This displays whatever day it is today. However, the date stored in $xmas2011 is independent of $today. The following code displays “Sunday”:

echo $xmas2011->format('l');  // Sunday

Using the -> operator is very similar to passing a variable as an argument to a function. Instead of putting the variable between the function’s parentheses, you attach the function (method) to the variable with the -> operator. What it actually means is “use the format() method with the value stored in this object ($xmas2011)”. In addition to format(), the DateTime class has other methods, such as setDate() and add(), that can be used to modify the date.

Many objects also have properties that you can access. An object’s properties are similar to values stored in an array. The big difference is that the class definition can control how a property is accessed and modified by specifying whether it’s public, protected, or private. Only public properties are visible and can be modified outside the class definition; protected and private ones are hidden from view. You access a public property using the -> operator like this:


This is the equivalent of accessing an array element like this:


If you’re familiar with JavaScript, it should be obvious by now that the -> operator plays the same role in PHP as the dot operator in JavaScript. For example, in JavaScript, this produces the date for Christmas Day 2011:

var xmas2011 = new Date(2011, 11, 25); // months are zero-based
alert('Christmas 2011 is on ' + xmas2011.toString());

JavaScript also uses the dot operator for properties:


Hopefully, that clarifies the role of the -> operator. If you still have questions, post them in the Comments section below.

This entry was posted in Books, PHP. Bookmark the permalink.

26 Responses to Accessing PHP objects’ methods and properties

  1. Jim Wright says:

    Thank you so much for this information. Although I have been working with computers since the 80’s, I do not consider myself a programmer. Some of the concepts are hard to learn all at once. The part that really struck home for me was your statement that “Using the -> operator is very similar to passing a variable as an argument to a function. Instead of putting the variable between the function’s parentheses, you attach the function (method) to the variable with the -> operator.” This has really helped. Jim Wright

  2. David Powers says:

    Glad that sorted it out for you, Jim. If PHP Solutions ever makes it to a third edition, that explanation will be added. Getting feedback from readers on what they find difficult to understand is a big help in improving my books.

  3. Maryhellen says:

    I’ve bought both your edition of “php solutions” and have been able to build a customized contact form with CC field dinamically filled with $email and $name variable. I ‘m not a programmer but now, in the updated code, i don’t understand how to add an additional headers with email recipient (dinamically) and name in the Cc field. I tried harder but nothing seems to work. Can you tell me if is possible to achieve this result so recipient can get a copy of the sent message? The code that worked in the first edition code is:

    // create additional headers
    $additionalHeaders = 'From: Arcobaleno96';
    if (!empty($email)) {
    // $additionalHeaders .= "\r\nReply-To: $email";
    $additionalHeaders .= "\r\nCc: $nome ";}

    Thanks a lot

  4. David Powers says:

    Hi Maryhellen,
    Fixing it in the updated code is almost exactly the same as before. Amend the code in step 2 on page 123 as follows:

    if (!$suspect && !empty($email)) {
    $validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if ($validemail) {
    $headers .= "\r\nReply-To: $validemail";
    $headers .= "\r\nCc: $name < $validemail>";
    } else {
    $errors['email'] = true;

  5. Maryhellen says:

    Thank you very much.
    Here are results:
    $headers .= “\r\nCc: $name “;
    does not work unless it becomea like this:
    $headers .= “Cc: $email”;

    Last question: is it possible to add some line of text before and after data field, i.e. for informations about company?
    For example:
    Your request

    nome: Mary
    message: bla bla

    Company name

    Thanks again

  6. David Powers says:

    You surprise me that you need to put the name and email on different lines, but if you’ve got it working, that’s all that really matters.

    As for adding text before or after a particular field, you can do that by adding conditional statement(s) to the end of the loop that builds the message in Just looking at the example you have given here, I would initialize the $message variable at the beginning of the loop like this:

    $message = "==============\r\n";
    $message .= "Your request\r\n";
    $message .= "==============\r\n";

    Then at the end of the loop:

    if ($item == 'address') {
    $message .= "Company name\r\n";
    $message .= "==============\r\n";
    $item = str_replace(array('_', '-'), ' ', $item);
    // add label and value to the message body
    $message .= ucfirst($item).": $val\r\n\r\n";

  7. Maryhellen says:

    Thanks, now it ‘s clear for me that if I’d like to add a sort of footer “preprinted” at the end of the message with web site contact info like this for example:

    Company name site owner
    Melrose place, 578 Ca

    i can’t use foreach loop because the text above is not before an input field ( ‘address’ is not a variable). Instead, it seems to me, i have to build this part of text message manually.
    Did i understand?
    Finally, the last question: what if i’d like to make required a checkbox (default state not checked) for the privacy acceptance (with his alert message in case user don’t check checkbox) ? In your book there is an example of an array for a group of checkbox and i’m struggling to make things work. Thanks. Sorry if i’m annoying you with all this questions.

  8. David Powers says:

    You can’t put the footer inside the foreach loop in, but you can put it outside the loop just before the line that passes the message to the wordwrap() function:

    // add footer here
    $message .= 'My Wonderful Company';
    // limit line length to 70 characters
    $message = wordwrap($message, 70);

    As for making a single check box required, don’t add square brackets after the name in the form (name="privacy"). Then follow the instructions in step 2 on page 137. It says “When dealing with a single check box, use an empty string instead of an empty array.” In other words:

    if (!isset($_POST['privacy'])) {
    $_POST['privacy'] = '';

    You don’t need step 3, but you should create an error message as described in step 4.

  9. Maryhellen says:

    Thanks, thanks , thanks
    I was struggling try to guessing solutions and when you gave me it seemed so elegant.
    It’s (sadly) clear to me that understand logic behind php and especially develop skills to build elegant, efficient, hacker-proof php script is – if is even possible for me- a long, long
    way. Thanks again.

  10. David Powers says:

    Learning how to write your own scripts or adapt existing ones does take time. I remember my own learning process. Loops, in particular, caused me a lot of problems. A loop just repeats the same action(s) over and over, but you can change what happens by using conditional statements inside the loop. You also need to consider if a particular procedure, such as your footer, can be handled outside the loop.

    Keep practising, and I’m sure you’ll get there in the end.

  11. Maryhellen says:

    For more future complex script I’ll ask you a quote.
    Thanks, also for your kindness.

  12. Maryhellen says:

    Here I’m again, I’d follow your instructions to make required privacy checkbox but i get an error.
    this is code:

    $required = array('nome', 'email', 'privacy');
    if (!isset($_POST['privacy'])) {
    $_POST['privacy'] = '';


    Please cheched privacy acceptance

    <input name="privacy" id="privacy" type="checkbox" value="accepted"

    here is the error as soon as I click submit button :
    Warning: in_array() []: Wrong datatype for second argument in /home2/maryhell/public_html/ASSOCIAZIONE PROGETTO BENESSERE/newsletter.php on line 121

    Can you help me? where is my error?

    Thanks a lot

  13. Maryhellen says:

    missing code from previous message:


    Please check privacy

    <input name="privacy" id="privacy" type="checkbox" value="accepted"


  14. David Powers says:

    The error is being caused by using in_array(). Because you’re not using a check box group, you also need to change the PHP error checking in the form like this:

    <input type="checkbox" name="privacy" id="privacy" value="accepted"
    if ($_POST && isset($_POST['privacy'])) {
    echo 'checked';
    } ?>>
    <label for="privacy">Accept privacy policy</label>

  15. Maryhellen says:

    Now it works but error message when checkbox is not checked do not display.
    this is code based on step 4 :

    Please accept privacy policy

    I’m very grateful to you

  16. Maryhellen says:

    for some reasons i not be able to show you code. Anywat it is step 4 page 138.

  17. David Powers says:

    The reason you can’t display code is because you’re trying to use tags other than those listed. To display other tags, you need to replace the opening angle bracket with &lt; and the closing bracket with &gt;.

  18. David Powers says:

    OK, I see where your problem lies. Since it’s likely to help others who might encounter the same issue, I have outlined the solution in the book’s updates and errors page. If the book ever goes to a third edition, I’ll create separate instructions for check box groups and individual check boxes.

  19. Maryhellen says:

    Great! everithin works fine. Thanks a lot. have a great week end

  20. Another percolator here says:


    Thanks so much for the explanations and code snippets, I am not that far yet but I will make note of it before it becomes an issue. My concern is, when I read the Configuration page some of my settings where not the same as the example, display_errors: STDOUT instead of On, when I changed the php.ini file to off it was fine. Also my error_reporting read 6135 ( my shared server is running 5.2.17 ) and the book shows 6143, is this going to be an issue as well ? Just want to make sure there are no snags when I get rolling.

    Thanks again for your time and knowledge !

  21. Maryhellen says:

    Hi, can i ask you a question about automatically indicating the current page (chap. 4 pg. 77)? Everything work until every page is on the same path level (root elevel), but what if some pages are in different directory (e.g. artiicle.php in “articles” folder, resource.php in “resource” folder and so on) . Is there a solution to make code more flexible for pages with different path? Thanks

  22. David Powers says:

    Hi Maryhellen,

    I’m currently travelling in the United States, and don’t have a copy of the book or files with me. I’ll look at the issue when I get back to the UK in 10 days’ time.

  23. David Powers says:

    @ Another percolator here: I have replied to you directly. Basically, it looks as though you have edited the wrong version of php.ini. You need to run phpinfo() and check the value of “Loaded Configuration File” to find out which version of php.ini is being read by your server.

  24. Maryhellen says:

    Hello, please can you help me to make required also only a selected element in a check box group with error message? In your book on page 137 (second edition) you present only the solution in case at least 2 elements selected are required… Maybe i can use it or there is a better solution ? Thanks as always.

  25. Maryhellen says:

    The most important thing is getting error messages just above check box group as the others fields

  26. Maryhellen says:

    last thing: i got “array” value but not the selected checkbox value