PHP Classes: When to Use :: VS. ->

PHP Classes: when to use :: vs. -?

Simply put, :: is for class-level properties, and -> is for object-level properties.

If the property belongs to the class, use ::

If the property belongs to an instance of the class, use ->

class Tester
{
public $foo;
const BLAH;

public static function bar(){}
}

$t = new Tester;
$t->foo;
Tester::bar();
Tester::BLAH;

When to use a Class vs. Function in PHP

Classes are used for representing data as objects. If you're representing something like a user's data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class).

Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer.

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.

PHP: Difference between - and ::

$name = $foo->getName();

This will invoke a member or static function of the object $foo, while

$name = $foo::getName();

will invoke a static function of the class of $foo. The 'profit', if you wanna call it that, of using :: is being able to access static members of a class without the need for an object instance of such class. That is,

$name = ClassOfFoo::getName();

What is the difference between class and function in php?

The PHP Language reference has details on what a function and class is:
http://www.php.net/manual/en/langref.php

It also explains most the other features of PHP. If want to learn PHP that is the best place to start.

Functions

The function is a grouping of statements (lines of code).

For example the following statements:

$name = 'mary';
$gender = 'girl';
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;

Can be grouped together into a function so it can be reused:

getSentence('mary', 'girl');
getSentence('peter', 'boy');
function getSentence($name, $gender) {
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;
}

Notice the two function calls:

getSentence('mary', 'girl');
getSentence('peter', 'boy');

These two statements run the whole block of code inside the getSentence function and pass it the variables $name and $gender.
With the first function $name = 'mary' and $gender = 'girl' and in the second $name = 'peter' and $gender = 'boy'.

So the main benefit of functions is that you have grouped code for reuse, allowing the passing of different values for the variables needed by the function. These variables are called the function parameters.

Another benefit of having the code grouped is easier readability. You are essentially naming the block of code, and giving them a specific purpose. Making it easy to read and remember it's use.

Another benefit is that redundancy is removed. You do not have to write the block of code more then once. You just define it once, and call it multiple times. This also makes editing of the function code affect all calls to that function - which reduces errors in having to edit multiple locations when changing just one aspect.

eg:

We can make sure the $name string has an uppercase first character.

function getSentence($name, $gender) {
$name = ucfirst($name);
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;
}

We made just one change, and it affected every function call to getSentence(). In this case both:

getSentence('mary', 'girl'); 

and

getSentence('peter', 'boy'); 

Classes are a grouping of functions.

class Play {
function getSentence($name, $gender) {
$name = ucfirst($name);
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;
}
function getSong($name) {
// code here
}
}

All we did was put

class Play { /** functions here **/ }

around a group of functions.

This offers the same benefits that functions do for statements except classes does it for functions.

Classes go further to build a programming methodology called Object Oriented programming (OOP), which you can read more about in link to PHP Language reference.

This defines classes as the template or definition of Objects. Objects being similar to real world objects, with the functions being called "methods" that can be called for the object.

So the class Play can be thought of as the object called "Play" with the methods "getSentence" and "getSong". These methods can then manipulate the properties of the object "Play" or return useful information about "Play". In this way, all the code inside Play becomes independent of code elsewhere in the program.

When the code inside Play requires some code elsewhere to function, it can be brought in using "inheritance", which is a major part of OOP. I will not go into detail about this as it is a very broad topic.

I would recommend getting a book on OOP and reading it to really understand why you should use classes and methods and when to use them.

PHP Classes: Should I use 2 classes or 1?

As with anything, there are many approaches with their own advantages and disadvantages.

My (current) preference is to combine class methods (static) and object methods for handling groups of objects and individual objects, respectively.

Consider the following code:

class Survey {
public $id;
public $uid;
public $rate;
public $reason;
public $complete;
public $opinion;

public function save()
{
drupal_write_record('survey', $this);
}
/**
* Loads survey from secondary storage
*
* @param string $id Unique surevy ID
*/
public function load( $id ) {
// loads a survey from secondary storage
}
/**
* Returns report of survey results.
*
* @param array $surveys array of surveys to process. If not passed or NULL,
* The whole set of completed surveys will be processed.
* @return string HTML Formatted report
*/
public static function compile_results( $surveys = NULL )
{
if( empty( $surveys ) )
{
$surveys = self::get_completed_results();
}
foreach( $surveys as &$survey )
{
// process an individual survey, possibly aggregating it
}
}
/**
* Retreives completed surveys from secondary storage.
*
* @return array Array of completed Survey objects
*/
public static function get_completed_surveys()
{
$surveys = array();
// Select all surveys from secondary storage
$survey_rows = array(); //replace with code to get surveys
foreach( $survey_rows as $survey_row )
{
$survey = new Survey();
$survey['id'] = $survey_row['id'];
$survey['uid'] = $survey_row['uid'];
$survey['rate'] = $survey_row['rate'];
$survey['reason'] = $survey_row['reason'];
$survey['complete'] = $survey_row['complete'];
$survey['opinion'] = $survey_row['opinion'];

$surveys[] = $survey;
}
return $surveys;
}
}

You can use the static methods to work with groups of objects. You could even have a static array holding a reference to each loaded survey.

Another option is to have a "Surveys" class whose purpose is to work with groups of surveys. The previous approach feels cleaner to me.

Classes vs. Functions

Create a function. Functions do specific things, classes are specific things.

Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.

When should I use 'self' over '$this'?

Short Answer

Use $this to refer to the current
object. Use self to refer to the
current class. In other words, use
$this->member for non-static members,
use self::$member for static members.

Full Answer

Here is an example of correct usage of $this and self for non-static and static member variables:

<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;

function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}

new X();
?>

Here is an example of incorrect usage of $this and self for non-static and static member variables:

<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;

function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}

new X();
?>

Here is an example of polymorphism with $this for member functions:

<?php
class X {
function foo() {
echo 'X::foo()';
}

function bar() {
$this->foo();
}
}

class Y extends X {
function foo() {
echo 'Y::foo()';
}
}

$x = new Y();
$x->bar();
?>

Here is an example of suppressing polymorphic behaviour by using self for member functions:

<?php
class X {
function foo() {
echo 'X::foo()';
}

function bar() {
self::foo();
}
}

class Y extends X {
function foo() {
echo 'Y::foo()';
}
}

$x = new Y();
$x->bar();
?>

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

From http://www.phpbuilder.com/board/showthread.php?t=10354489:

By http://board.phpbuilder.com/member.php?145249-laserlight

difference between :: and - in calling class's function in php

The :: syntax means that you are calling a static method. Whereas the -> is non-static.

MyClass{

public function myFun(){
}

public static function myStaticFun(){
}

}

$obj = new MyClass();

// Notice how the two methods must be called using different syntax
$obj->myFun();
MyClass::myStaticFun();


Related Topics



Leave a reply



Submit