I have a parent class, that calls a new facebook class within it. However, I then have another class that extends the parent, and tries to read the facebook class within it, but it dies everytime.
Any ideas?
Thanks!
My psychic debugging skills tell me that your subclass is not calling the parent constructor, so the facebook class is not being created.
If you're in PHP5, try adding parent::__construct(); to the subclass's constructor, possibly with some extra parameters. Otherwise, you might need to do: $this->SuperclassName(); with some extra parameters as well.
Related
I have looked online for the meaning of parent::init(); . All I was able to find was that init() is to initialize some settings which want to be present every time the application runs.
Can anyone please explain the meaning of parent::init() in exact sense, like significance of both the words?
Thanks in advance.( I am sorry if its too simple! )
When we use parent::init(), we are just calling the parent method (in this case init()) inside a method of the current class.
About parent::
For example, let's say we have a class called MyClass. This class have a awesome method that runs alot of things:
class MyClass
{
public function runStuffs()
{
// trigger events, configure external stuff, adding default values to properties.
}
}
Now, after some time, we decided to create a new Class that extends from the first one. And we called MySecondClass:
class MySecondClass extends MyClass
{
}
It already have the method runStuffs(), but, for this second class, we need to do more things in this method, but maintaining what it have.
Sure we could rewrite the whole method and just copy and paste what we have in MyClass and add the new content. But this isn't elegant or even a good practice. what if later on We change the method in MyClass, you probably would like that MysecondClass have that changes too.
So, to solve that problem, we can call the parent method before write your new content:
class MySecondClass extends MyClass
{
public function runStuffs()
{
parent::runStuffs();
// do more things!
}
}
Now MySecondClass->runStuffs() will always do what its parent do and, after that, more stuff.
About the init() method.
init() is a method used in almost all classes from Yii2 framework (since most of then extends from yii\base\Object at some point) and works just like the __constructor() method (native from PHP). But there is some differences, you can read more here.
Actually the init() method is called inside the __constructor(), and the framework encorage us to use init() instead of __construct() whenever is possible.
Now if both are pretty much the same thing, why do they create this method? There is an answer for that here. (take a look at qiang's answer, from the dev team):
One of the reasons for init() is about life cycles of an object (or a component to be exact).
With an init() method, it is possible to configure an object after it is instantiated while before fully initialized. For example, an application component could be configured using app config. If you override its init() method, you will be sure that the configuration is applied and you can safely to check if everything is ready. Similar thing happens to a widget and other configurable components.
Even if init() is called within constructor rather than by another object, it has meaning. For example, in CApplication, there are preInit() and init(). They set up the life cycles of an application and may be overridden so that the customization only occurs at expected life cycles.
Conclusion
So, when you use a init() method and calls parent::init() you are just saying you want to add more things to that method without removing what it already was doing.
The parent::init(); Method is useful to execute a code before every controller and action,
With an init() method, it is possible to configure an object after it is instantiated while before fully initialized.
For example, an application component could be configured using app config.
If you override its init() method, you will be sure that the configuration is applied and you can safely to check if everything is ready.
Similar thing happens to a widget and other configurable components.
In Yii, init() method means that an object is already fully configured and some additional initialization work should be done in this method.
For More Information check this link :
https://stackoverflow.com/questions/27180059/execute-my-code-before-any-action-of-any-controller
Execute my code before any action of any controller
might be helpful to you.
For my latest website I'm trying to use OOP. I'm using the project to develop my understanding of this technique. Previously I would 'include' a functions folder that contains various php files labelled things like image.upload.functions.php and general.error.handling.functions.php etc.
However, this time I'm using classes wherever possible.
I have just read that in order to use a parents methods (in an extended class) you must run the parents constructor however I haven't done this and my project seems to work ok.
So.. I have a class called Form Validation
I have another class called Process Login that extends Form Validation.
My Form Validation class does things like test a password strength to make sure it is strong enough, check whether a user is in the database etc.
I extend Form Validation with a Registration class and a Forgotten Passowrd class.
Should I be putting:
parent::_construct();
..in the constructor of each of the extended classes?
Could someone explain 'simply' the reasons why we do OR do not do this? And whether it's something I should be doing?
Many thanks :-)
Here's the link to official documentaion: constructors and destructors
And here's the quote:
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
Calling parent constructor is NOT necessary. And, in general, it is not called implicitly, if You have defined constructor in Your own child class. But, if in the parent constructor You have a nice piece of logic or functionality, that You don't want to lose, then call parent's constructor from the child's one.
You call parent::__construct() (watch that there are two underscores) if you want to reuse the functionality of the constructor from the class you're extending.
The reuse of code is a main reason for inheritance in OOP. So if there is any algorithm in your parent class that you want to use, you have to call parent::__construct().
If you're extending the parent's constructor, you also have to call it before (or after) your own additions, e.g. like this
class A extends B {
public __constructor() {
parent::__construct();
// Your own code
}
}
If you don't want to use any of your parents' constructor functions, you don't inherit from that parent constructor - but I assume that in most cases you want to.
I'm very new to codeigniter ,
I wanted to know what is the meaning of a constructor in a controller . I saw the following code in a codeigniter tutorial -
class upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(form);
}
// rest of the class...
My question is when is the constructor invoked - is it called every time the controller serves a request (e.g the controller class is instantiated for each request it receives?)
Well, that's a more general PHP question. Anyway, yes, the magic method __construct() is called (automatically) upon each instantiation of the class, as you can see in the manual: http://www.php.net/manual/en/language.oop5.decon.php
Usually, in CI is not necessary to call a constructor, unless you actually want one. In the example you posted, the code loads the helper on every instantiation of the class - which is the same as loading the helper in every method, just saves a lot of typing and ensures it's not forgotten. You can alternatively put the library/helper/model you want to have alywas loaded in the respective autoload array in config/autoload.php (check "autoloading" in CI's manual)
Once you define a constructor in your child Controller you're compelled to call the parent constructor (of the mail CI_Controller class), because there is where the main CI object is created and all the classes are loaded, and you need those in your child controller too; if fail to do so your child class will construct separately and won't inherit.
I hope I made myself clear, english is not my mothertongue :)
the constructor is magic Literally its called a magic method.
what makes the constructor cool is that it will do things for you BEFORE any of the methods. So if you have an admin class, and someone should be logged in in order to access it - you can check for login in the constructor and bounce them out if they are not authorized.
in the constructor you can load the models, libraries, helpers, etc that your class needs, and they will be available for any method in the class.
you can load in variables that are used by methods. this is really useful for models.
Don't use _construct() function in latest apache & codeigniter
Use helperlin in index() function
That's a general question. Constructor is a function that is automatically called when instantiated. this function helps us to intialize the things that we are going to need frequently in our code like when we have to load the models of helpers like form e.t.c.
$this->load->model('Model_name');
now when you write this line in your constructor you don't need to load this model again and again in your methods of that class.
I've just started experimenting with OO PHP, but there's one basic principle I don't really uderstand that well, and don't find too much info on it.
When creating a __construct() method, why would you want it to be public, when it's specifically a constructor for that class?
When would you want to call a constructor outside the class?
To me, it seems using a protected constructor is good practice, right?
I know this is basic OO stuff, but I don't find any info directly on it, specifically for constructors.
The __construct (not "__constructor") method is the one called when you do new MyClass(), i.e. when you instantiate the class. The constructor needs to be public, unless you only want to instantiate the class from within itself. If the latter, you need at least one other public static method you can call in which the class will instantiate itself, otherwise you're unable to create any instance of it.
Whenever you create a new instance of a class, the constructor is called. If the constructor is not public, no other code can create an instance of that class.
Hence, if you want to create instances of the class, make the constructor public.
A constructor is always only part the class it is defined in, I don't understand what you mean by "when it's specifically a constructor for that class".
To clarify:
The only way to invoke the constructor is with new Class(). There is no other way to invoke it. __construct is a magic method and there is no way to explicitly call a magic method.
I am new to OO concepts in PHP. I have a class called MY_ controller which is my base class. All classes extend this class. I am using MVC architecture. I am using caching in my system now. So i load the cache variable in the constructor of my base class. I use normal php variable like $cacheVariable in my function to store the value from cache. I was wondering if it would serve any help if i store it as a class parameter and use like $this->cacheVariable? In each function i get cache value like $this->cache->get('cacheVariable'); will it help if i get value from $this->cacheVariable
If you want to be able to use $cacheVariable anywhere else besides your constructor you'll want to use $this
public function __construct() {
//...
$this->cacheVariable = $this->cache->get('cacheVariable');
//...
}
Also remember, if you want your children classes to inherit this variable from your base class you will need to set it as either public or protected. If it's private children will not inherit it.
When you say "class variable" I assume you are referring to a property (property of an instance=. Note the difference:
if you have a class, say MyClassA, then in your scripts you will instantiate that class using the operator new (depending on your PHP version you can use a different constructor syntax it changed since PHP-5.3.0):
<?php
class MY_controller{
public $cacheVariable;
// constructor
function MY_controller($aValue){
// constructor code which loads cacheVariable, for example with parameter
$this->cacheVariable = $aValue;
}
public function someFunction(){
//... some code, then access the property
$cv = $this->cacheVariable;
}
}
$aController = new MY_controller(42);
?>
As you inherit from MY_controller, every instance of that class, will have access to cacheVariable through $this->cacheVariable.
The important thing I wanted to clarify is that it is an instance property, not a class one. For further reference on OOP in PHP, refer to the properties section in PHP's OOP manual and the inheritance section.
When you instantiate only one instances of your controller (derived from your main controller), its a conceivable solution.
In my opinion the better idea is getting variable directly from cache service everywhere you want in your class and don't keep it as a class property. The reason is simple: let's say value of some key from cache will be changed (or expires) in the other place than your class. If you have this value as class property you need to keeping eye on it every time you access this value but if you retrieving it from cache you just don't care (because the cache cares if value of some key doesn't changed or expired).