Welcome Guest, Not a member yet? Register   Sign In
use of $this
#1

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
{
   protected $data = array();
   function __construct()
   {
       parent::__construct();

       $this->data['brand'] = 'myCompany';
.....
And now,  another Controller extends MY_controller. It has a method that loads a view and passes $data to this view, like this:
Code:
$this->load->view('start.php', $this->data);
It's works and it is handy, but is it OK, is it good practice?
Reply
#2

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.
Reply
#3

(12-02-2016, 08:40 AM)Narf Wrote: 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.

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?
Reply
#4

(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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB