Jump to content

calling a class


Xdega

Recommended Posts

This is probably a quick one. I am pretty new to OOP, in fact somewhat a novice. I am working a lot more with objects lately as my previous "flat" php experience doesn't allow me to create clean and expandable applications. Of course though, questions will always pop up (that's what you guys are for?)

 

One concept I am having trouble understanding, is the method to call a class.

 

What is the difference between?:

 

<?php $cat = new class(); ?>

 

and just simply:

 

<?php  new class(); ?>

 

Both appear to have the same output from my small amount of practice, but the first way seems strange to me. Being that I am very new to OO PHP, the first way looks like it is just defining a var. But in reality it is calling the class and running it? This seems very backwards to me and I am having a hell of a time understanding it. I am aware that the first way seems to be the "proper" way, but just can't fathom it.

 

Could someone explain this to me a little further?

thanks much,

Link to comment
https://forums.phpfreaks.com/topic/231059-calling-a-class/
Share on other sites

A constructor is a function/method with an implicit return value - an object of that class.  In order to capture and handle this new object, it needs to be stored in a variable, else it'll be inaccessible.  It's no different than any other function that returns a value, with the exception that an explicit return statement isn't used.  For that reason, version 1 is the way to go and version 2, while technically syntactically correct as well, is useless.

Link to comment
https://forums.phpfreaks.com/topic/231059-calling-a-class/#findComment-1189387
Share on other sites

A class doesn't 'run'.  A class is a blueprint for a custom type.  An object is an instance of that class*.  To create a new object, a special method known as a constructor is executed.  A constructor is ALWAYS executed, regardless of whether or not you define one in your class.  If you don't define one, PHP's default constructor is executed.  All this does is inform the interpreter that a new object of that type now exists.

 

*A type is generally described as data which adheres to certain criteria and the actions that can work on that data.  An example would be integers.  They represent data of a certain criteria (whole numbers) and allow certain actions to work on that data (mathematical operations).  An instance of an integer would be 4.

Link to comment
https://forums.phpfreaks.com/topic/231059-calling-a-class/#findComment-1189394
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.