5

I've used php enough to be quite comfortable with it, but recently I've been looking through some MVC frameworks to try and understand how they work, and I've come across a syntax and data structure which I haven't encountered before:

function view($id)   
   {   
       $this->Note->id = $id;   
   }

What is the ->id section of this code? Is this a sub-method based off it's parent method? If so, how do I go about writing code to create such a structure? (ie. creating the structure from scratch, not using an existing framework like the above example from cakephp).

hakre
  • 193,403
  • 52
  • 435
  • 836
Richard
  • 347
  • 1
  • 4
  • 5
  • possible duplicate of [Absolutely basic PHP question about the "-> " syntax](http://stackoverflow.com/questions/4502587/absolutely-basic-php-question-about-the-syntax) – Gordon Feb 11 '11 at 17:01
  • *(related)* [Reference: What does this symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon Feb 11 '11 at 17:02
  • This would be a method in a class. See http://www.php.net/manual/en/language.oop5.basic.php – Nabab Feb 11 '11 at 17:02
  • It's `$note = $this->Note; $note->id = $id` – Gordon Feb 11 '11 at 17:03
  • It essentially means that $this->Note is itself an object with the proprety $id. – Joe Green Feb 11 '11 at 17:06

3 Answers3

3

The following code demonstrates how one could arrive at the structure you described.

<?php

class Note
{
    public $id = 42;
}

class MyClass
{
    public function __construct() {
        // instance of 'Note' as a property of 'MyClass'
        $this->Note = new Note();
    }

    public function test() {
        printf("The \$id property in our instance of 'Note' is: %d\n",
            $this->Note->id);
    }
}

$mc = new MyClass();
$mc->test();
?>
Jon Nalley
  • 511
  • 2
  • 8
2

Note is a property of $this and it's (current) value is an object with a property named id which gets assigned the value of $id.
If id was a method of the Note object, the line would read $this->Note->id($id);.

rik
  • 8,592
  • 1
  • 26
  • 21
1

Another way to think about the construct is considering

 $this->Note->id = $id;

similar to

 $this["Note"]["id"] = $id;

Which would actually be equivalent if both objects ($this and subobject Note) were based on ArrayAccess.

mario
  • 144,265
  • 20
  • 237
  • 291