![]() |
use of $this - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12) +--- Thread: use of $this (/showthread.php?tid=66783) |
use of $this - muuucho - 12-02-2016 Is it ok to assign data into $data in a Controller using $this in order to make it accessablethrough any method in any "child" controller Code: class MY_Controller extends CI_Controller Code: $this->load->view('start.php', $this->data); RE: use of $this - Narf - 12-02-2016 If you want to use inheritance - that's its whole purpose. It can be argued whether inheritance is good in the first place, but since you pretty much can't get without it in CodeIgniter, that's a moot point. RE: use of $this - 040mag - 12-03-2016 (12-02-2016, 08:40 AM)Narf Wrote: If you want to use inheritance - that's its whole purpose. I'm new to OOP and CI and I have two questions here: 1. Is it better to access "$data" the OOP way ("$this->data") as in muuuchos example or should I access it by "$data" as the CI documentation does, and are the two ways technically equivalent? 2. Then a basic question about inheritance. Lets say I have a class "Car" that inherits "MY_Controller". Should I access "$data" (or "$this-data") direct or is it better to declare it "private" in "MY_Controller" and then use getter and setter functions? In other words: is it good practice to use data encapsulation when you want to access data from a class that you inherit from? RE: use of $this - Narf - 12-03-2016 (12-03-2016, 03:23 AM)040mag Wrote: 1. Is it better to access "$data" the OOP way ("$this->data") as in muuuchos example or should I access it by "$data" as the CI documentation does, and are the two ways technically equivalent? These are not different ways of accessing the same thing. It's 2 different things, neither is better. (12-03-2016, 03:23 AM)040mag Wrote: 2. Then a basic question about inheritance. Lets say I have a class "Car" that inherits "MY_Controller". Should I access "$data" (or "$this-data") direct or is it better to declare it "private" in "MY_Controller" and then use getter and setter functions? In other words: is it good practice to use data encapsulation when you want to access data from a class that you inherit from? The latter is not possible - private symbols are only accessible from inside the class that declares them. Even if you call a getter declared in MY_Controller, it will still be executed inside the context of Car, and the property will be inaccessible. |