Function - Differences between methods in PHP and Ruby

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m just beginning to learn PHP. Sorry, if it s a newbie question but I m wondering how methods work. For example, if I wanted to remove white spaces at the beginning of a string. In Ruby, I would call something like:

string.strip!

But in PHP, I would have to do something like:

trim(string);

Obviously, the Ruby version is more elegant(in terms of object-oriented design), but I m wondering how it works for PHP and other languages such Java. Is there a name for designing functions/methods this way(in PHP)? And where are those methods defined and why can they be accessed anywhere? Thanks a lot in advance!

Answers

There are two different paradigms here: object-oriented programming (OOP) and procedural programming .

In OOP, functions are defined in the context of data, encapsulated by classes  ; such functions are usually called methods . When a method is called on an object (e.g. an instance of a class), it inherently has access to the state of that object. So, in your example, strip already knows what string it s being called on, and so doesn t require any additional arguments. Whenever your function naturally operates on a particular object or set of data (e.g. as strip acts on a string), it is sensible to define it as an instance method in this way.

In procedural programming, functions are defined independently data structures (classes), and must be explicitly passed the data they are to work with. Sometimes this approach is in fact more natural; for example, a print function that prints some input to stdout, or similar, isn t naturally associated with any particular object or data.

Most modern languages have OO features built into them, as it s a very versatile and powerful programming paradigm. Languages like Java and C# encourage all code to be written in an object-oriented style. In these languages, even the basic data-types like strings and floating points are in fact objects and have their own methods and state. This is particularly true in C#, where all types inherit ultimately from System.Object (even int and double) and inherit all the common methods defined thereby. This is called a unified type hierarchy .

PHP, on the other hand, has a curious mixture of OOP and procedural features; it started life as a procedural language, and OOP was only introduced in version 3 (and only in a very rudimentary sense). While, as of PHP5, it has relatively good OOP support, most of its standard library is still implemented procedurally as loose collections of functions that expect to have the relevant state/data passed to them as arguments. OOP libraries are becoming more common, however (e.g. with mysqli).

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/12998200/differences-between-methods-in-php-and-ruby

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils