PHP OOP

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
In interpreted programming languages, such as PHP and JavaScript, what are the repercussions of going with an Object Oriented approach over a Procedural approach?

Bottom line: how big (if any) is the performance hit really, when going with OO vs. Procedural in an interpreted language?
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
How long is a piece of string.

What really matters is writing code that is self documenting, extensible, easy to understand and maintain; not only for you, but also for any unfortunate buggers who are expected to fix bugs and/or add new features to your code. Overzealous separation and encapsulation of code can bloat call stacks and will certainly make editing code for maintenance purposes more difficult.

Personally I don't like OOP at all; Functional Programming is my preference, far easier to test, extend and maintain.

Functional Programming like its mathematical namesake, always yields the same value for a particular input, it deals specifically with immutable state where the order of evaluation does not have to be well-defined; because of this approach, functional code is generally easier to parallelize (multi thread). By design functions hace no side effects, which in constrast OOP & procedural code always do; where mutable state and hidden inputs are common place.

In practice though you're going to use a bit of each; e.g. you can't easily avoid OOP when it comes to event driven processing, e.g. UI; but in practice I write no more than 20% OOP, the rest tends to follow FP principles.
 
Last edited:

Hamish McPanji

Honorary Master
Joined
Oct 29, 2009
Messages
42,088
I largely use procedural because I spaghetti code. But OOP is a much neater way of doing this
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
To be honest I don't know what I use I just know whatever I am doing is logically sense if that makes sense...?

Since I am a noob I have to have my system so that if I look at it after a month it still explains itself.

I like to make my own little functions for reusable code example.

My own lorem ipsum generator

So it well be

echo lorem(3);

That will give me 3 lorem ipsum paragraphs
Silly example but just to give some feedback
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
In maths for the following function "x + y = answer"; the answer will always consistenly provide the same answer for the same x, y inputs. e.g. "3 + 2 is always = 5"; the inputs are always well defined, and the inputs are immutable, meaning the input values 3 & 5 cannot be affected by another parallel process (that's why they're easy to parallelize).

OOP on the other hand deals with a lot of mutable and hidden inputs; hidden inputs refer to the use of e.g. variables that aren't defined as a parameter to a function, you gain access to these as part of the class and/or as part of the inheritance chain. These hidden inputs are problematic, because unless the programmer knows what they're doing, they can easily affect integrity by allowing in process mutation, meaning a input value could be changed after you enter a function call, and specifically before you complete all the related calculations, meaning the result can easily be indeterminate.

Similarly in procedural coding global variables can offer similar risks to OOP hidden inputs and mutable state.
 
Last edited:

Hamish McPanji

Honorary Master
Joined
Oct 29, 2009
Messages
42,088
echo lorem(3);

That will give me 3 lorem ipsum paragraphs
Silly example but just to give some feedback

OOP comes into its own when you get to things like inheritance.

So for example if you have Assets which consist of : vehicles, aircraft , boats, generators, etc

You can define a generic Asset object which applies to all assets , so Name, GUID, Colour, etc

You then have a Vehicle object which inherits the properties of the Asset object , and adds additional properties , so VIN # , Engine #, Engine Capacity, Tyre size, Fuel Type ,etc

You then have a Aircraft object which inherits the properties of the Asset object , and adds additional properties , Tail #, Passenger Capacity, etc

You can see how you have already reduced the coding as you don't have to define the generic properties for each type of Asset.

You can go further, and create a Car, Motorcycle, Truck, Lorry, Bus object which inherits the properties of the Vehicle object

You can query the database of Assets , and read in all the properties into an object you create based on one of the fields. So if the 2nd field is "Asset Type" and has a value of "Vehicle", then in your code

New Vehicle()
Vehicle.Name= dbo.field("Name")
Vehicle.VIN = do.field("VIN")

etc.

It's efficient, and quick. The downside is you need to be able to think in a very logical manner. And so like database normalisation is often a skill that is inherent or learnt after a very long time of blunders.

In my experience, people struggle more with the design rather than implementation. And often realise very late in the development where they have failed
 

BandwidthAddict

Expert Member
Joined
Apr 19, 2005
Messages
2,380
OOP comes into its own when you get to things like inheritance.

So for example if you have Assets which consist of : vehicles, aircraft , boats, generators, etc

You can define a generic Asset object which applies to all assets , so Name, GUID, Colour, etc

You then have a Vehicle object which inherits the properties of the Asset object , and adds additional properties , so VIN # , Engine #, Engine Capacity, Tyre size, Fuel Type ,etc

You then have a Aircraft object which inherits the properties of the Asset object , and adds additional properties , Tail #, Passenger Capacity, etc

You can see how you have already reduced the coding as you don't have to define the generic properties for each type of Asset.

You can go further, and create a Car, Motorcycle, Truck, Lorry, Bus object which inherits the properties of the Vehicle object

You can query the database of Assets , and read in all the properties into an object you create based on one of the fields. So if the 2nd field is "Asset Type" and has a value of "Vehicle", then in your code

New Vehicle()
Vehicle.Name= dbo.field("Name")
Vehicle.VIN = do.field("VIN")

etc.

It's efficient, and quick. The downside is you need to be able to think in a very logical manner. And so like database normalisation is often a skill that is inherent or learnt after a very long time of blunders.

In my experience, people struggle more with the design rather than implementation. And often realise very late in the development where they have failed
OOP != Inheritance. In fact, inheritance is to be used sparingly. Encapsulation and composition are more what OOP is about. Keep it simple and it will be maintainable.

BTW, OOP is a technique that is very hard to do right; most get it very wrong.
 

Hamish McPanji

Honorary Master
Joined
Oct 29, 2009
Messages
42,088
OOP != Inheritance. In fact, inheritance is to be used sparingly. Encapsulation and composition are more what OOP is about. Keep it simple and it will be maintainable.

BTW, OOP is a technique that is very hard to do right; most get it very wrong.
We can go into detailed analysis of different features of OOP and what they advantages and disadvantages of each are, but I think that that is beyond the scope of this thread. Have seen people **** up in a spectacular way whatever they use.

The idea is to inspect the problem properly and map out the solution properly before a line of code is written.

The example I gave was an example specifically for the purpose of procedural vs OOP. My opinion is similar to what the guy here says : https://www.thoughtworks.com/insights/blog/composition-vs-inheritance-how-choose
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
I used to think that everything I write should be extensible and cover every use case that might appear in the future.

Now I write clean maintainable code to fulfil the requirements, and refactor as new use cases emerge.

http://c2.com/cgi/wiki?ThreeStrikesAndYouRefactor
Well said.

It may be called software engineering, but it's nothing like engineering. We certainly don't spend months elaborately detailing plans, sourcing materials, ..., prior to the construction. It's just the opposite; we iterate through a multitude of construction models until we discover the one that best supports the need; the concept of building up, testing and tearing down to start over is quite normal; and easy to do.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
BTW, OOP is a technique that is very hard to do right; most get it very wrong.
Exactly...
In the beginning, there was spaghetti code.
And Dijkstra said, ‘Let there be Structured Programming! Thou shalt consider goto harmful and organize your code into functions with proper control flow mechanisms.’
And programmers said, ‘OK, sure we’ll do that.’
Then Dijkstra saw that code was still spaghetti and said, ‘Stop sharing state willy-nilly! Thou shalt avoid global variables and instead pass all state through the call graph.’
And programmers said, ‘Er, um, wait, really? We haven’t really figured out this functional programming thing, nor do we want to pay the overhead of immutable data on today’s machines, so what you’re proposing is horribly impractical and inconvenient for non-trivial programs.’
But the programmers did agree that shared state was problematic and that maybe they could cut back on all these global variables. And so Object-Oriented Programming was born, and the global variables lived happily ever after disguised as singleton object fields.
 
Last edited:

cguy

Executive Member
Joined
Jan 2, 2013
Messages
8,527
To answer the OP's question: I doubt that given PHP's current implementation, OOP would make any performance difference, one way or another.

I do agree with all the criticisms of OOP thus far though. I use it sparingly, and only when it makes sense. If a reader can't grok my class hierarchy in under 5 minutes, I've failed. I also never have any classes called XYZManager ;-)
 

halfmoonforever

Expert Member
Joined
Feb 1, 2016
Messages
1,196
OOP > Procedural in terms of performance from what I've experienced, especially if you are expecting a few thousand hits a second.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
From the web:

However there is one thing about those two apps that the pro-OOP crowd never like to admit. That is that if you gave the code to a sampling of PHP programmers, the vast majority would go for the procedural code because it is simply easier for most PHP programmers to understand. And that's why there are so many successful PHP apps with procedural code.

I think the one problem with OOP that never gets mentioned is that it is a methodology driven by consultants who make their living on "the new."
 

Spacerat

Expert Member
Joined
Jul 29, 2015
Messages
1,328
From the web:

Would say that it is true, but not because procedural is better. It's because of procedural coding legacy and most programmers have not made the mindshift to OOP.

Personally I only use OOP. Classes and objects everywhere. Even for a monetary value (Read up on Value Objects). The benefits are huge. Read up on the O in SOLID. The latter relates directly to code quality.

And then code reuse. Once I have written a class that does something it gets properly tested and promoted to my own library assemblies. I have reused code/classes that I wrote more than 15 years ago. Still use them on new projects. Yes, on occasion I do a bit of refactoring. If your classes are not well defined and written and tested, yes it will be a mess. Especially so if you do not honour SRP. But that is not OOP fault. It's yours.

When you are talking about deep class hierarchies, then you are doing it wrong. Deeper inheritance hierarchies are fine when you want to inherit properties, but not so much when you inherit behaviour. Favour loose composition rather than inheritance. Personally I use inheritance max 3 levels deep to implement behaviour for a set of similar classes. And then the base class is abstract and the derived classes do the minimum. Only implementation specific stuff.

Code that uses OOP should not be a mess. If you name the classes and methods properly to indicate intent, the code reads far better. E.g

Currency usd = new Currency("USD");
Currency zar = new Currency("ZAR");
ExchangeRate exchangeRate = exchangeRateProvider.Get(DateTime.Today,usd,zar);

Money salaryInUsd = new Money(1000.00m,usd);
Money salarayInZar = salaryInUsd.ConvertoTo(zar,exchangeRate);
Money bonusInZar = new Money(1000);
Money totalEarnings = salaryInZar + bonusInZar;
Money junk = salaryInUsd + bonusInZar; // throws exception

So you ask why use the Money class instead of decimal? Well, the Money class guarantees that my value holds true to my domain rules. I.e. the overloaded + operator will not allow addition of values of diff currencies. Decimal would. And that is a mistake easily made in your code that results in a bug. Secondly, the Money class ensures that the value sticks to 2 decimals, e.g. after the ConvertTo method. I dont have to explicitly round it afterwards. Yet another thing that if you forget it (and its easy), will be a likely bug.
 
Last edited:

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
I use a lot of functions not sure if that counts for anything?

I basically have all my pages like this:

HTML:
<php require_once("db_connection"); ?>
<php require_once("functions.php"); ?>
<php include("header.php"); ?>
<php include("menu.php"); ?>
<main>
<!-- body content -->
</main
<php include("footer.php"); ?>
<php require_once("db_close.php"); ?>
 

halfmoonforever

Expert Member
Joined
Feb 1, 2016
Messages
1,196
From the web:

"Most programmers" are idiots/drones trying to churn out as much code per hour to satisfy their overlords.

Any programmer worth their salt will and CAN read OOP code perfectly without getting confused.

Now, are there programmers who totally go insane in OOP and overcomplicate things? yes.

Because there are so many fly-by-night "I can code cuz I can reed gud" making money out of people with no technical knowledge, when you take over their code you hope to G-d that it's procedural in a semi-coherent form
 

halfmoonforever

Expert Member
Joined
Feb 1, 2016
Messages
1,196
I use a lot of functions not sure if that counts for anything?

I basically have all my pages like this:

HTML:
<php require_once("db_connection"); ?>
<php require_once("functions.php"); ?>
<php include("header.php"); ?>
<php include("menu.php"); ?>
<main>
<!-- body content -->
</main
<php include("footer.php"); ?>
<php require_once("db_close.php"); ?>

Good start, at least it's better than the stuff I've seen before

PHP is like the R5 hooker on the corner of the street. Sure you can do anything and as much as you'd like and it's cheap and quick... but STD-prone if not used right
 

Spacerat

Expert Member
Joined
Jul 29, 2015
Messages
1,328
Ok so to further the Money class example and illustrate the open/closed principle.

Let's say you work in financial services and your money resolution needs to be more than 2 decimals.

So then you create a new class


public class HiResMoney
{
public HiResMoney(int precision)
{
// Validate precision here
this.precision = precision;
}

protected override decimal RoundValue(decimal value)
{
return Math.Round(value,precision);
}

private readonly int precision;
}


So by using the open/closed principle we do not touch the Money class but instead extend it. The RoundValue virtual method in the Money class uses 2 by default. If you didn't implement the virtual method in the Money class, you have to implement it but the impact on that class is minimal and easily re-tested. This exercise would literally take you 30secs.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Let me stir the pot; the only programmers still doing exclusively OOP are probably too dense to grasp FP concepts :whistling:

Don't be scared by functional programming; the concepts like anything else need to be studied, and it'll take time to master; but there's much to gain....here's a few PHP code examples to demonstrate some of this.
PHP:
//-------------------------------------------------------------------
// Imperative
$sum = 0;
for($i = 1; $i <= 10; $i++) 
{
	$sum += $i; 
}
print "$sum \n";

// Functional
print array_sum(range(1,10)) . "\n";  // 55

//-------------------------------------------------------------------
// Imperative
$arr = array(1,2,3,4,5,6,7,8,9,10);
$sum = 0;
foreach($arr as $value)
{
	$sum += $value; 
}
print "$sum \n";

// Functional
print array_sum(array(1,2,3,4,5,6,7,8,9,10)) . "\n"; // 55

PHP:
//-------------------------------------------------------------------
// Imperative
$input = array('o', 'g', 'o');
$output = "";
foreach($input as $value)
{
	$output .= strtoupper(++$value);
}
print "$output \n"; // PHP

// Functional
$input = array('o', 'g', 'o');
print join("", array_map(function($v) { return strtoupper(++$v); }, $input)) . "\n"; // PHP

PHP:
//-------------------------------------------------------------------
// Imperative
$arr = array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
$result = array();
foreach($arr as $value)
{
	$sum = 0;
	for($i = 0; $i <= $value; $i++)
	{
		$sum += $i;
	}
	array_push($result, $sum);
}
print join(",", $result) . "\n"; // 55,210,465,820,1275,1830,2485,3240,4095,5050

// Functional (Combining Higher Order Functions)
$arr = array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
print join(",", array_map(function($v) { return array_sum(range(0, $v)); }, $arr)) . "\n"; 
// 55,210,465,820,1275,1830,2485,3240,4095,5050

PHP:
//-------------------------------------------------------------------
// Functional (Head Recursion, FYI other FP languages usually favour tail optimization.)
function head_sum($v) 
{ 
	return $v == 1 ? $v : $v + head_sum($v - 1); 
}
print head_sum(100) . "\n"; // 5050

These additional examples I unfortunately had to screenshot as Mybroadband thinks I'm trying to hack it (some keyword is scaring cloudfare)
Screen Shot 2016-08-17 at 11.08.27 AM.png

Oh and while I'm on the OOP topic, here's some more salt on that wound.
 
Last edited:
Top