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!
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).
You're looking at, essentially, the different between instance methods and class/static methods. Instance methods are called on a specific instance of a class, and they have access to the internal state of that instance. Class/static methods are not, and do not.
I'm not sure what you're looking for in asking "how it works for PHP and ... Java." With regard to instance vs non-instance methods, Ruby, PHP, and Java all work roughly the same.
Related
What is the name of having code structured with methods attached to objects?
For example:
" ... ".trim
or
obj.method()
At first many would argue this is Object oriented, but php is Object Oriented(well partially), yet it syntax is completely different trim(" ... ").
TL;DR "Object Oriented" and "Everything is an Object" aren't valid answers unlesss......
People constantly suggest PHP is "Object Oriented" and libraries are "Object Oriented", yet PHP library's code is often structured with tons of static classes.
For example RedBean:
R::dispense($bean)
R::store($bean)
R::trash($bean)
That doesn't follow the obj.method syntax, yet is supposedly Object Oriented. Is PHP's object orientation misleading, or is there a better name for obj.method() coding style.
PHP can do both. You can write object oriented code, and you can write procedural code.
Procedural code is much easier to understand and write, and most PHP programmers don't really understand OOP, so they write, what I call, procedural code disguised as OOP.
This includes things like static methods, and singletons.
Much of the core functions of PHP is C heritage, so don't get surprised if it doesn't follow OOP conventions.
The important thing is that calling methods on objects does follow OOP conventions.
Strings in PHP are not considered to be objects but scalar values. Therefore the syntax "..."->trim() cannot work unless the scalar string literal is converted to object first.
There is an open proposal for auto-boxing (auto-converting of a scalar value to object). This would allow the usual object oriented syntax. Auto-boxing, however does have a little performance penalty. See more here:
https://wiki.php.net/rfc/autoboxing
In the case of RedBeanPHP I use static methods for the facade. This is more user friendly than purist OO code. You don't have to know about all the internals of RedBeanPHP in order to use it (there is also an OO way to use the lib). In my opinion RedBeanPHP is really object oriented; behind the facade it uses inheritance, interfaces, polymorphism and patterns like adapters, factories, observers.
Also, I believe OOP is more like a way of thinking than just a syntax thing. For instance you can just as well craft object oriented systems using structs and function pointers or like GTK does. OOP features in languages are just to facilitate. Also, because PHP is a dynamic language (in contrast to static typed) it does not have to rely on types, it can just scan objects for desired behaviours. In my opinion this is a good thing because it is more flexible and more maintainable the deep class hierarchies like in Java. I used to be an OO purist but I have recently embraced OOP-pragmatism; just use the best of both worlds.
I have been reading around the definition of OOP and couldn't get why PHP is considered object oriented.
Can this have anything to do that the "basic level" of PHP isn't and more advanced features are?
OO features were added to PHP in stages through versions 3-5, after much of the standard library had already been created and the language was already established. Background
For this reason the standard library is not object-oriented and so everyday PHP scripts need not use any OO-style features at all. Although PHP by now has most of the standard features of an object-oriented language, many authors don't use them.
Library functions added to the language later continued to use functional style for consistency, though many extension modules do use objects.
Almost any language that allows you to create and instantiate classes can be considered object oriented.
PHP has these capabilities, but doesn't really stretch them. You can use OOP to help your code, but it isn't required. Java and C# barely allow you to write non-OO code, as everything must be in a class.
Can this have anything to do that the "basic level" of PHP isnĀ“t and more advanced features are?
You could say that about just about any OO language. The general definition of OO code is where you create classes and instantiate them in your code, calling methods on them from other classes. Nothing stops you from using only static methods or one super class with a 'run' method that only calls other methods inside the class, both of which would definitely NOT be object oriented. As far as I know, there aren't any languages that say "You must create classes and instantiate them or you will be banished!" (I haven't looked into Smalltalk though).
Beginners often learn the basics while putting all their code in just one method that gets called at the stat of the program. Once they get to more 'advanced' features like methods and classes, they are offered other options.
There is already a sufficient (and accepted) answer here, but I thought I'd throw another log on the fire for clarity's sake.
The "class" keyword (and the enforcement of its ubiquity, as in Java) does not Object-Oriented Programming make. As CrazyJungleDrummer pointed out, it is perfectly feasible (and all too common) to write entirely procedural code in something like Java; the fact that the code lies between curly braces in a class called HelloWorld doesn't change that fact. And just hiding a bunch of functions in a class and calling them static methods isn't OOP either -- it's namespacing.
Think of a proper object as a struct (or "custom type", depending on your previous language exposure) that knows what to do. Objects are data that you don't (or shouldn't) act upon directly; you ask them to do things to themselves, and you ask them to tell you about themselves. You create entities and pass messages. OOP is about treating your data like it's all grown up and can handle itself. It's not about where the main line of code lives, but how data are treated.
Oh, and one more thing -- even in a language that is more obviously canted toward OOP, real OOP is not always the right approach. It's all about the data.
You can write classes with PHP, but most of the core features are not object-oriented.
It's been a long time since this question but I came upon this article and wanted to shre the author's point of view.
PHP is not object oriented!
This answer is inspired by this Man and his answer.
Object-Oriented technology is often described in
terms of encapsulation, polymorphism, and inheritance. But
these are only identity.
If object-oriented technology is to be successfully
it must emphasis on the object.
When we say Object-oriented or Object-orientation it can refer to several things:
Object-oriented analysis and design[OOAD]
Object-oriented design[OAD]
Object-oriented database
Object-oriented modeling
Object-oriented operating system
Object-oriented programming[OOP]-->topic of concern
Object-oriented software engineering
Object-oriented user interface
What Pure Object Oriented Programming Language[OOP] is?
Alan Kays["Considered by some to be the father of object-oriented programming"] [Defination]5 link by Gordon:
EverythingIsAnObject.
Objects communicate by sending and receiving messages (in terms of objects).
Objects have their own memory (in terms of objects).
Every object is an instance of a class (which must be an object).
The class holds the shared behavior for its instances (in the form of objects in a program list)
Now clearly it can be seen Java,C++ and PHP violates rule 1?Why bcoz int, float etc. (there are a total of eight primitive types). so it cannot be Object oriented in strict sense but some folk's considered it as OOP.
The general approach of OOP is to view a software system as a collection of interacting entities called "objects" each of which is defined by an identity, a state described in terms of member variables, and a behavior described in terms of methods that can be invoked
What OOP is not?
Object-Oriented technology is often described in
terms of encapsulation, polymorphism, and inheritance. But
these are only identity.
An Object Oriented system, language, or environment should include at least Encapsulation, Polymorphism, and Inheritance.
Polymorphism and Inheritance are certainly patterns that facilitate
OO programming, but not only bound to it
The object-oriented paradigm isn't completely the domain of
high-level programming languages -->may topic of debate but i came
across this OOP in Assembly
Uncle Bob aka Bob Martin in his lecture shows How C implements Encapsulation,Inheritance,and Polymorphism LINK
OO is based on modeling real-world objects // For Marketing purpose
Difference Between OOP and Functional?
This may be not be perfect answer but i gave a try,Thnks to knowledge of valley.
Note:
Images are randomly found on google
I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
Do Interfaces were created in another languages because they don't provide multiple inheritance? Or am I missing something more important here?
First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires.
It's a lot like comparing the number 7 and the color green. They're both nouns. Beyond that, you're going to have trouble comparing the two.
Here's the bottom line.
Python does not need interfaces.
Java requires them.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
The two concepts have almost nothing to do with each other.
I can define a large number of classes which share a common interface. In Python, because of "duck typing", I don't have to carefully be sure they all have a common superclass.
An interface is a declaration of "intent" for disjoint class hierarchies. It provides a common specification (that can be checked by the compiler) that is not part of the simple class hierarchy. It allows multiple class hierarchies to implement some common features and be polymorphic with respect to those features.
In Python you can use multiple inheritance with our without interfaces. Multiple inheritance can include interface classes or not include interface classes.
Java doesn't even have multiple inheritance. Instead it uses a completely different technique called "mixins".
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
If you create an interface in Python, it can be a kind of formal contract. A claim that all subclasses will absolutely do what the interface claims.
Of course, a numbskull is perfectly free to lie. They can inherit from an interface and mis-implement everything. Nothing prevents bad behavior from sociopaths.
You create an interface in Java to allow multiple classes of objects to have a common behavior. Since you don't tell the compiler much in Python, the concept doesn't even apply.
Do Interfaces were created in another languages because they don't provide multiple inheritance?
Since the concepts aren't related, it's hard to answer this.
In Java, they do use "mixin" instead of multiple inheritance. The "interface" allows some mixing-in of additional functionality. That's one use for an interface.
Another use of an Interface to separate "is" from "does". The class hierarchy defines what an objects IS. The interface hierarchy defines what a class DOES.
In most cases, IS and DOES are isomorphic, so there's no distinction.
In some cases, what an object IS and what an object DOES are different.
The usefulness of an interface is directly connected to the usefulness of static typing. If you're working in a dynamically-typed language like PHP or Python, interfaces truly don't add significantly to the expressiveness of the language. That is, any program that can be described as using interfaces can be expressed without significant difference without using interfaces.
As a result, Python has a fairly nebulous concept of a "protocol" (an implementation conforming to a certain pattern, like the iteration protocol) which amounts to essentially the same thing, but without the other benefits of compile-time checking its value is limited.
In a statically-typed language, on the other hand, an interface is essential to allow implementation to be decoupled from implementation. In a static language, the types of all expressions must be resolved at compile time, so normally bindings to implementation must be made at that time, limiting run-time flexibility. An interface defines how to access functionality without defining a specific implementation, which allows a static language to prove that expressions are correct without having access to the implementation.
Without interfaces (or an equivalent formulation like C++'s pure virtual functions), the expressiveness of a statically-typed language would be severely hampered. In fact, many implementations exist (Win32 and COM come immediately to mind) to essentially reproduce much of the functionality of interfaces and virtual dispatch in C by storing function pointers in structures (and thus re-implementing C++'s virtual functions and vtable invocation by hand). In this case there is a big difference in expressiveness, since many changes are required in the program to express the same concepts.
Interfaces are just one example of type polymorphism, and a fairly limited one at that. In languages that support parametric polymorphism (aka generics) you can accomplish much more. (For example, C#'s LINQ would not be possible without generic interfaces.) For a much more powerful form of the same kind of thing, look into Haskell's typeclasses.
Even in duck-typed languages like Python, an interface can be a clearer statement of your intent. If you have a number of implementations, and they share a set of methods, an interface can be a good way to document the external behavior of those methods, give the concept a name, and make the concept concrete.
Without the explicit interface, there's an important concept in your system that has no physical representation. This doesn't mean you have to use interfaces, but interfaces provide that concreteness.
In dynamically typed languages, like PHP and Python, interfaces are only of limited use. You can already attempt to call methods on any object whenever, and you get a run-time error if it doesn't exist.
It's in statically typed languages, like Java and .NET, that interfaces become important, because methods and their arguments are checked at compile-time.
Now, for interfaces:
Java has Lists in addition to arrays. As a general rule, arrays are for primitives (the number types mainly), while Lists are for objects.
I can have a List<String>, which is a list of strings. I know I can add strings to it, and get strings back from it.
I don't know which implementation it is. It could be an ArrayList (list backed by an array), a LinkedList (list backed by a doubly linked list), a CopyOnWriteArrayList (thread-safe version of ArrayList), etc...
Thanks to polymorphism and interfaces, I don't need to know which type of List it is to do List operations on it.
Because you want to program against an interface and not a concrete implementation (GoF 1995:18)
Because sometimes you don't want to provide an implementation.
Java Interface
Java class
Yes. As for PHP, interfaces are just a means to overcome the lack of multiple inheritance. There are minor semantic differences useful for IDEs, and fewer conflicts caused by interfaces clearly aid newbie programmers. But as said before, it's not strictly necessary in dynamic languages.
http://c2.com/cgi/wiki?MultipleInheritance
Please read Twisted Framework article about power of Zope Interfaces in python.
It's generally implemented to replace multiple inheritance (C#).
I think some languages/programmers use them as a way of enforcing requirements for object structure as well.
What is the best way to deal with "utility" functions in a OOP PHP framework? Right now, we just have a file with several functions that are needed throughout the system. (For example, a distribute() function which accepts a value and an array, and returns an array with the value distributed in the same proportions and same keys as the input array.)
I have always felt "dirty" using that because it's not object-oriented at all. Is it better practice to move these into various classes as static methods, or is that just a semantic workaround? Or is there just going to be a level in a framework where some stuff is going to fall outside of the OOP structure?
I tend to make a Util() class that contains only static methods, has no attributes, and is not inherited from. Essentially, it acts as a "namespace" to a bunch of utility functions. I will allow this class to grow in size, but will occasionally split of methods into their own classes if it is clear that those methods are designed only to work with certain kinds of data or if it is clear that a group of related methods should be grouped into a class along with, perhaps, some attributes.
I think it's perfectly OK to deviate from purely OOP practices so long as the code that deviates is well-organized and is not creating architectural flaws in your system that make it harder to understand and maintain.
I've always been more pragmatic about questions like these.
If you want to go full-OOP, you should obviously stick these into classes. However, these classes are only going to be container classes, because they don't really represent objects of any kind.
Also: using classes would require you to either have an instance of that class, using the singleton pattern or declaring every function static. The first one is slower (okay, might not be that much, but in a large framework things like that get large, too - especially in interpreted languages like PHP), while the second and third ones are just plain useless and simply an OOP wrapper for a set of functions (especially the third approach).
EDIT: Feel free to prove me wrong. I might be. I'm not too experienced and always saw it that way, but I might be wrong.
I always think of utility functions as extensions of the standard php functions. They are not object oriented because you don't really get any benefit from making them OO.
In static languages like Java you need interfaces because
otherwise the type system just won't let you do certain things.
But in dynamic languages like PHP and Python you just take
advantage of duck-typing.
PHP supports interfaces.
Ruby and Python don't have them.
So you can clearly live happily without them.
I've been mostly doing my work in PHP and have never really
made use of the ability to define interfaces. When I need a
set of classes to implement certain common interface, then
I just describe it in documentation.
So, what do you think? Aren't you better off without using
interfaces in dynamic languages at all?
I think of it more as a level of convenience. If you have a function which takes a "file-like" object and only calls a read() method on it, then it's inconvenient - even limiting - to force the user to implement some sort of File interface. It's just as easy to check if the object has a read method.
But if your function expects a large set of methods, it's easier to check if the object supports an interface then to check for support of each individual method.
Yes, there is a point
If you don't explicitly use interfaces your code still uses the object as though it implemented certain methods it's just unclear what the unspoken interface is.
If you define a function to accept an interface (in PHP say) then it'll fail earlier, and the problem will be with the caller not with the method doing the work. Generally failing earlier is a good rule of thumb to follow.
Interfaces actually add some degree of dynamic lang-like flexibility to static languages that have them, like Java. They offer a way to query an object for which contracts it implements at runtime.
That concept ports well into dynamic languages. Depending on your definition of the word "dynamic", of course, that even includes Objective-C, which makes use of Protocols pretty extensively in Cocoa.
In Ruby you can ask whether an object responds to a given method name. But that's a pretty weak guarantee that it's going to do what you want, especially given how few words get used over and over, that the full method signature isn't taken into account, etc.
In Ruby I might ask
object.respond_to? :sync
So, yeah, it has a method named "sync", whatever that means.
In Objective-C I might ask something similar, i.e. "does this look/walk/quack like something that synchronizes?":
[myObject respondsToSelector:#selector(sync)]
Even better, at the cost of some verbosity, I can ask something more specific, i.e. "does this look/walk/quack like something that synchronizes to MobileMe?":
[myObject respondsToSelector:#selector(sync:withMobileMeAccount:)]
That's duck typing down to the species level.
But to really ask an object whether it is promising to implement synchronization to MobileMe...
[receiver conformsToProtocol:#protocol(MobileMeSynchronization)]
Of course, you could implement protocols by just checking for the presence of a series of selectors that you consider the definition of a protocol/duck, and if they are specific enough. At which point the protocol is just an abbreviation for a big hunk of ugly responds_to? queries, and some very useful syntactic sugar for the compiler/IDE to use.
Interfaces/protocols are another dimension of object metadata that can be used to implement dynamic behavior in the handling of those objects. In Java the compiler just happens to demand that sort of thing for normal method invocation. But even dynamic languages like Ruby, Python, Perl, etc. implement a notion of type that goes beyond just "what methods an object responds to". Hence the class keyword. Javascript is the only really commonly used language without that concept. If you've got classes, then interfaces make sense, too.
It's admittedly more useful for more complicated libraries or class hierarchies than in most application code, but I think the concept is useful in any language.
Also, somebody else mentioned mixins. Ruby mixins are a way to share code -- e.g., they relate to the implementation of a class. Interfaces/protocols are about the interface of a class or object. They can actually complement each other. You might have an interface which specifies a behavior, and one or more mixins which help an object to implement that behavior.
Of course, I can't think of any languages which really have both as distinct first-class language features. In those with mixins, including the mixin usually implies the interface it implements.
If you do not have hight security constraints (so nobody will access you data a way you don't want to) and you have a good documentation or well trained coders (so they don't need the interpreter / compiler to tell them what to do), then no, it's useless.
For most medium size projects, duck typing is all you need.
I was under the impression that Python doesn't have interfaces. As far as I'm aware in Python you can't enforce a method to be implemented at compilation time precisely because it is a dynamic language.
There are interface libraries for Python but I haven't used any of them.
Python also has Mixins so you could have create an Interface class by defining a Mixin an having pass for every method implementation but that's not really giving you much value.
I think use of interfaces is determined more by how many people will be using your library. If it's just you, or a small team then documentation and convention will be fine and requiring interfaces will be an impediment. If it's a public library then interfaces are much more useful because they constrain people to provide the right methods rather than just hint. So interfaces are definitely a valuable feature for writing public libraries and I suppose that lack (or at least de-emphasis) is one of the many reasons why dynamic languages are used more for apps and strongly-typed languages are used for big libraries.
Rene, please read my answer to "Best Practices for Architecting Large Systems in a Dynamic Language" question here on StackOverflow. I discuss some benefits of giving away the freedom of dynamic languages to save development effort and to ease introducing new programmers to the project. Interfaces, when used properly, greatly contribute to writing reliable software.
In a language like PHP where a method call that doesn't exist results in a fatal error and takes the whole application down, then yes interfaces make sense.
In a language like Python where you can catch and handle invalid method calls, it doesn't.
Python 3000 will have Abstract Base Classes. Well worth a read.
One use of the Java "interface" is to allow strongly-typed mixins in Java. You mix the proper superclass, plus any additional methods implemented to support the interface.
Python has multiple inheritance, so it doesn't really need the interface contrivance to allow methods from multiple superclasses.
I, however, like some of the benefits of strong typing -- primarily, I'm a fan of early error detection. I try to use an "interface-like" abstract superclass definition.
class InterfaceLikeThing( object ):
def __init__( self, arg ):
self.attr= None
self.otherAttr= arg
def aMethod( self ):
raise NotImplementedError
def anotherMethod( self ):
return NotImplemented
This formalizes the interface -- in a way. It doesn't provide absolute evidence for a subclass matching the expectations. However, if a subclass fails to implement a required method, my unit tests will fail with an obvious NotImplemented return value or NotImplementedError exception.
Well, first of all, it's right that Ruby does not have Interface as is, but they have mixin, wich takes somehow the best of both interfaces and abstract classes from other languages.
The main goal of interface is to ensure that your object SHALL implement ALL the methods present in the interface itself.
Of course, interface are never mandatory, even in Java you could imagine to work only with classes and using reflection to call methods when you don't know wich kind of object you're manipulating, but it is error prone and should be discouraged in many ways.
Well, it would certainly be easier to check if a given object supported an entire interface, instead of just not crashing when you call the one or two methods you use in the initial method, for instance to add an object to an internal list.
Duck typing has some of the benefits of interfaces, that is, easy of use everywhere, but the detection mechanism is still missing.
It's like saying you don't need explicit types in a dynamically-typed language. Why don't you make everything a "var" and document their types elsewhere?
It's a restriction imposed on a programmer, by a programmer. It makes it harder for you to shoot yourself in the foot; gives you less room for error.
as a PHP programmer, the way I see it, an Interface is basically used as a contract. It lets you say that everything which uses this interface MUST implement a given set of functions.
I dunno if that's all that useful, but I found it a bit of a stumbling block when trying to understand what Interfaces were all about.
If you felt you had to, you could implement a kind of interface with a function that compares an object's methods/attributes to a given signature. Here's a very basic example:
file_interface = ('read', 'readline', 'seek')
class InterfaceException(Exception): pass
def implements_interface(obj, interface):
d = dir(obj)
for item in interface:
if item not in d: raise InterfaceException("%s not implemented." % item)
return True
>>> import StringIO
>>> s = StringIO.StringIO()
>>> implements_interface(s, file_interface)
True
>>>
>>> fp = open('/tmp/123456.temp', 'a')
>>> implements_interface(fp, file_interface)
True
>>> fp.close()
>>>
>>> d = {}
>>> implements_interface(d, file_interface)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in implements_interface
__main__.InterfaceException: read not implemented.
Of course, that doesn't guarantee very much.
In addition to the other answers I just want to point out that Javascript has an instanceof keyword that will return true if the given instance is anywhere in a given object's prototype chain.
This means that if you use your "interface object" in the prototype chain for your "implementation objects" (both are just plain objects to JS) then you can use instanceof to determine if it "implements" it. This does not help the enforcement aspect, but it does help in the polymorphism aspect - which is one common use for interfaces.
MDN instanceof Reference
Stop trying to write Java in a dynamic language.