0

What is going on in this statement?

$this->load->view("index.php");

I've seen this syntax in CodeIgniter and elsewhere where the code is inside a class, hence "$this", and it is referencing "load" or some other method which is then pointing to a method/function it looks like.

Can someone explain to me what "load" is in this? Not in the CodeIgniter context but general PHP. How would i write a class that allows for this?

I tried the following but it doesn't work.

<?php

class myObject {

    private $x = 0;

    function amethod()
    {

       function embeddedFunc()
       {

            $this->x += 7;

            return $this->x;
       }

       return embeddedFunc();
    }
}

$object = new myObject();

echo $object->amethod->embeddedFunc();

?>

I'm trying to wrap my head around what's actually happening when i see this.

2
  • 4
    Load is not a method in your example. It is a property that, if I had to guess, holds an object with a method view(). Commented Feb 4, 2013 at 19:48
  • This is the CI object, load is the controller, view is the method. What you're doing is not following this pattern. In your case, un-nest that function and just put it at the same level as the other one then call it $object->embeddedFunc() Commented Feb 4, 2013 at 19:49

2 Answers 2

1

In this case load is a property of the class that is an object that has a view() function. For example:

class test {
    public $load;
    public function __construct() {
        $this->load = new test2();
    }
    public function step1() {
        $this->load->step3('Updated text');
    }
}
class test2 {
    public function step3($display_text) {
        echo $display_text;
    }
}
$tester = new test();
$tester->step1();

Since load is an instance of an object you can go ahead and run a function of that instance. Hopefully that helps.

Sign up to request clarification or add additional context in comments.

Comments

0

In PHP, $this-> is required to access a class member variable. It's a bit confusing, that you have to write this-> strictly, but other hand you don't have to declare it.

 class Foo {

   function bar() {

      $this->myVariable = 8;   // this is OK

   } // bar() 

 } // class Foo

So $this->load->view() refers to the current object's load property, which holds an object which has view() method. Train your eye to cut the leading this-> and train your hand to write it always. Just as you've already learned to write leading '$' mark always.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.