Jump to content

Recommended Posts

Hello mates,

Please leave you opinion in here if you feel confident about the answer for this subject.

A discussion in between me(php and C++ adventurer) and my mate(delphi pascal coder) was started. I use classes in php with static methods and construct a well based OOP code. His argumentations are:

 

1- If i use Classes with static methods rather than instance methods, my code will never be 100% OOP. (He said: "impossible 100% OOP with only static methods").

2- If I use arrays built in my classes and static methods I am escaping from OO. (He said: "rather than an array in a method of a class to manipulate 20 or more objects ie:'users', He would create one class  for each".

3 - I use " new className" call  to initiate magic methods such as __construct and only. He said: " 'new className' call is useless if you are using static methods" But he forgets I use the magic method __construct and others to start and manage any other method within the class or classes in my scope when needed.

 

The questions I'll leave are:

 

About 1-  Is it true my code is never 100% OOP just because I don't use the instance methods to start my class and because i don't like creating var instance for a class and consequently  not using the pointer -> and $this?

 

About 2 - Is it correct not use arrays in your methods because they will downgrade your OOP code and rather than that you would create as many classes as you need, ie, 20 classes just to store 20 users as objets and to not use arrays?  and then user upgrades 21, new class, 22 new class. rather than  a simple array, independently how complex you array can be within a unique class?

 

About 3 - Is it really "useless the use of  new className" when i am using class with static methods? I call it any time and sometimes after the class  is already in use running other methods. Again as I use static, I only call "new className" when i have magic methods to play for me, consequently having many other methods treated by the magic method of course if i don't call the "new className" it doesn't run and If I have the magic methods to use why would i create a new method in my class just to initiate the others i need?

 

I said I use arrays, and static methods in my classes becase of all the reasons mentioned above and I have a 100% OOP Logic in my source code. He said Impossible.

 

Shall I give up my 3 favourite ways to code and accept his experienced statements?

 

 

 

About 1-  Is it true my code is never 100% OOP just because I don't use the instance methods to start my class and because i don't like creating var instance for a class and consequently  not using the pointer -> and $this?

I wouldn't go as far as to say it isn't OOP. OOP serves many purposes, one of which is making something modular. For example, a class with a bunch of static functions used for validation. There is no real need for instance, and calling them like so:

validate::isEmail($email);
validate::isPhone($phone);

is valid use of OOP in my opinion. As you can see, there are valid cases for all static classes, but I think in some of your cases, you should not being using static classes (more below).

 

About 2 - Is it correct not use arrays in your methods because they will downgrade your OOP code and rather than that you would create as many classes as you need, ie, 20 classes just to store 20 users as objets and to not use arrays?  and then user upgrades 21, new class, 22 new class. rather than  a simple array, independently how complex you array can be within a unique class?

Vague speaking, there is nothing wrong with an array instead a method. But, you shouldn't be using it to store sets of information. First, to get some terminology straight, a 'class' is just the framework, while an object is a working instance of that class. Now, in your example of users, you should have a class called 'user'. And, create an instance of that class for each user. For example:

<?php
  class user {
    var $username;
    function __construct ($username) {
      $this->username = $username;
    }
  }
  $user1 = new user('bob');
  $user2 = new user('jane');
  print $user1->username;
  print $user2->username;
  }
?>

 

About 3 - Is it really "useless the use of  new className" when i am using class with static methods? I call it any time and sometimes after the class  is already in use running other methods. Again as I use static, I only call "new className" when i have magic methods to play for me, consequently having many other methods treated by the magic method of course if i don't call the "new className" it doesn't run and If I have the magic methods to use why would i create a new method in my class just to initiate the others i need?

yes, if you are using all static methods, then i don't see the use of 'new' and a constructor

 

 

if you provide a basic example of how you use OOP, I can provide feedback on what to change (if anything needs to be changed)

Haha

 

The term OOP refers to objects within a system and their interaction with each other. I could create 100 classes that do certain things when instantiated but does mean my system is object orientated. This is a common misconception that if I have classes in my system I am an OO programmer - rubbish. It is the UML for your system that displays the OO concept in your system.

 

Secondly static methods are used in various patterns for certain tasks i.e. instantiating objects. Lets say I want a new user object but it maybe a student, teacher or substitute

 

class x {
 public static function generate($x, $name) {
   switch($x) {
     case 1:
       return new student($name);
     break;
     case 2:
       return new teacher($name);
     break;
     case 3:
       return new substitute($name);
     break;
   }
 }
}

$user = x::generate(1, "Joe Bloggs");
$user->getName();

 

Classes should not consist entirely of static methods or properties (unless you have a really good reason for this). However with php4 you can still use the static type operator with classes ::

 

Using arrays within objects for the purpose of storing other objects is entirely feasible. For instance in my above example I could use this method to generate 20 student objects and they are placed within a 'classroom' object (as they are students of the class). I can easily get all the names of the students in the classroom. This is OO design!

 

You should always use the new syntax to create an object if it has a constructor that requires parameters that will be set as the class properties:

 

class student() {
 private $name;

 public function __construct($name) {
   $this->name = $name
 }

 public function getName() {
   return $this->name
 }
}

$user = new student("Joe Bloggs");
print $user->getName();

rhodesa mate, here is my sample why i use NEW caller;

<?php
//The example below clarifies why I don't use classes Instance methods but
//classes static methods, I like the look and feeling, perhaps performance
//by using statics, but lets not get there, it's my personal choice.
//Other thing is: PPL say, Why the heck use NEW if you are handling static methods?
//simple: Because i like using the static var scope to add whatever the magic method
//__construct brings to it, without the need of more literal creation in my code when i can.
//also when using magic methods NO WAY it can be static, that is why  "new class".
//PPL say by coding this way and by using arrays, I will never reach the objects and consequently
//I cannot make any OOP pattern using static methods in my classes. Do you all agree???
// This is just a sample for this discussion. No usability intent!
class userUpgrades {
     public static $usrsArray,
                   $userNow,
                   $Return,
                   $info;

     public function __construct($user){
         self::$userNow = $user;
         new returnAnalised;// LOOK the NEW here again.
     }

     public static function setUsrsCond($usr, $type){
         self::$usrsArray[$usr] = $type;//array gathers all dynamically no matter amount of users.
     }
}

class returnAnalised extends userUpgrades{
    public function __construct(){
        self::$Return = analiseConditions::analiseUsers();
        if(parent::$Return):
            echo "user side: <br />";
            echo parent::$info;
        else:
            echo "user side: <br />";
            echo parent::$info = "Good day ".parent::$userNow." nothing changed, you are a regular user.";
        endif;
    }
}
// The big deal is here: whenever i change, extend or whatever, the class UserUpgrades will never be touched.
//So i could have more conditions and more retunrs
class analiseConditions{

   public static $cond,
                 $condMax;

   public static function analiseUsers(){
        if (array_key_exists(userUpgrades::$userNow, userUpgrades::$usrsArray)):
            $usrCond = userUpgrades::$usrsArray[userUpgrades::$userNow];
            switch(TRUE):
                case $usrCond == "Guest Account"://Conditions can be dynamic from DB too, no need to be static
                    userUpgrades::$info =  "Sorry <b>".userUpgrades::$userNow."</b>,your account wasn't upgraded yet, Would you like to?";
                break;
                case $usrCond == "Merchant Upgrade":
                    userUpgrades::$info =  "Hello <b>".userUpgrades::$userNow."</b> congrats! You now hold a merchant account, $1000 Limit added.";
                break;
                case $usrCond == "Shopper Discount":
                    userUpgrades::$info = "G'day <b>".userUpgrades::$userNow."</b> 20% off today in all departments, exclusively for you";
                break;
            endswitch;
            return TRUE;
        else:
            return FALSE;
        endif;
    }

   public function __construct($c){
       self::$cond = $c;
       self::$condMax = array_count_values(userUpgrades::$usrsArray);
       if (in_array(self::$cond, userUpgrades::$usrsArray)):
          echo "<br /><br />Admin side:<br>Today <b>";
          echo self::$condMax[self::$cond];
          echo "</b> account types of <b>";
          echo self::$cond;
          echo "</b> is set for execution - Users will be warned once they login";
       endif;
    }

       public function __destruct(){
           //This is just to show a friend the use of
           //__destruct coz he said it its just used to
           //unset vars, destruct objects and rubish collector lol 
           //not really.
       if (self::$condMax[self::$cond] >= 2):
          echo "<br /><br />Admin Warning:<br> Account type: <b>";
          echo self::$cond;
          echo "</b> execeeds the max allowed upgrades per day - the excess will be removed from DB and set for tomorrow.";
       endif;
    }
}
// This can be extrated from the DB dynamically to fill the method arguments.
userUpgrades::setUsrsCond("Mick Doe", "Guest Account");
userUpgrades::setUsrsCond("Allan Doe", "Shopper Discount");
userUpgrades::setUsrsCond("Foo Bar", "Merchant Upgrade");
userUpgrades::setUsrsCond("Madonna", "Merchant Upgrade");
userUpgrades::setUsrsCond("Angelina Jolie", "Guest Account");
// this coud be a post of course, just after login or whatsoever implementation.
new userUpgrades("Angelina Jolie");//Change just here.
// this can be reuse in the Admin side, cheching all the upgrades that will happen.
new analiseConditions("Merchant Upgrade");// Reuse this class whitout affect the  analiseUsers() method
//Reminders:: i can I do use a lot of static method calls withou the use of new class caller.
//ie: analiseConditions::analiseUsers();
//But ins't the case in this topic, this example i wanted to illustrate the 3 questions I made based
//on the criticism i received for coding this way, I love PHP OO style, so I gotta love static keyword 
//saves from using globals, has a great visibiity control and it's cute LOL.
?>


 

neil.johnson, mate

I did appreciate your references as well, but you didn't get much into the dilema, he said:

 

You can never have a 100% OOP by using classes with only static methods but instance method.

If you use arrays in classes, it's not OOP then.

and my New usage as class caller is useless he said, well remove them from my scope in the sample i gave above. :)

 

And yes I may drawn myself into the static methods coz PHP4 is past for me and all my projects, I am already focusing in Var = 'class' as of php 5.3 and further more unicode implementation in php 6.

 

So, unless a bloke proves my "static" coding is rubish, I'll stick with it. that is the dilema here.

 

Cheers mate!

 

As your objects have no internal properties set and are not truly instantiated by using the new className() syntax with methods referenced by $this I would say that your implementations are truly unorthodox. Your design is a bit spaghetti like. I would really focus on using php5 as 4 is not truly object orientated.

 

Rather than using static method calls from one class to another as you have your methods should accept objects of the required type using class type hinting i.e.

 

<?php
class a {
public function sayHello(b $b) {
	print $b->getName()." says: Hello World";
}
}

class b {
public $name;

public function __construct($name) {
	$this->name = $name;
}

public function getName() {
	return $this->name;
}
}


$a = new a();
$a->sayHello(new b("Joe Bloggs"));
?>

 

You can use as many arrays as you like within your object. Arrays work differently in C++. This is why your friend has his argument. In C++ you have to declare the size of the array and are stuck with that limit for the duration of the program. For this reason arrays are created dynamically outside of the main class.

Using static everywhere is like a carpenter using only a screwdriver.  Yeah, they can probably hammer nails with it, but it's not the best tool for the job.

 

In your (Rangel's) example, as canned as it may be, I can't help but think that each user should be its own object.  It's just more efficient to have instance variables in cases like this.  Something like:

 

class User
{
   private $name;
   private $category;

   public function __construct($name)
   {
      $this->name = $name;
   }

   public function getName()
   {
      return $this->name;
   }

   public function setCategory($cat)
   {
      $this->category = $cat;
   }
}

class UserList
{
   private $users;

   public function __ construct($users)
   {
      $this->users = $users;
   }

   public function addUser($user)
   {
      $this->users[] = $user;
   }

   public function setCategory($userName, $cat)
   {
      for($i = 0; $i < count($this->users); i++)
      {
         if($this->users[$i]->getName() == $userName)
         {
            $this->users[$i]->setCategory($cat);
            return;
         }
      }

      echo "User not found";
   }
}

$angelina = new User("Angelina Jolie");
$brad = new User("Brad Pitt");
$jealous = new User("Jennifer Aniston");

$users = array($angelina, $brad, $jealous);

$userList = new UserList($users);
$userList->setCategory("Jennifer Aniston", "stalker");

 

It's not hard to envision UserList having a method to remove individual users from its internal array, as well.

 

To me, the code I wrote is far more clear than yours.  It deals with concrete entities, each with its own set of properties.  I can mix and match User objects whenever I want without compromising their integrity or the integrity of other components in the system.

 

Something else I just caught: While __construct may be a magic method, its purpose is to set properties and invoke other methods during object creation.  In other words, there's an implied usage expectation when using that method.  The way you're using it is both confusing, as you never intend to use the object that's briefly created, and ultimately pointless, as you don't need a child object there at all.

 

From what I can see, after looking at your code more while slowly waking up this morning, you pretty much miss the point of OOP.  I mean, data encapsulation is a big part of it, yet your class properties are publicly accessible, meaning they can be changed at any time.  You never create any objects (at least none that persist) - what if you wanted several arrays of users, based on their membership levels?  What if users had more info attached to them than their name and membership level?

 

There's a reason why it's termed Object Oriented Programming.

Using static everywhere is like a carpenter using only a screwdriver.  Yeah, they can probably hammer nails with it, but it's not the best tool for the job.

 

In your (Rangel's) example, as canned as it may be, I can't help but think that each user should be its own object.  It's just more efficient to have instance variables in cases like this.  Something like:

 

class User
{
   private $name;
   private $category;

   public function __construct($name)
   {
      $this->name = $name;
   }

   public function getName()
   {
      return $this->name;
   }

   public function setCategory($cat)
   {
      $this->category = $cat;
   }
}

class UserList
{
   private $users;

   public function __ construct($users)
   {
      $this->users = $users;
   }

   public function addUser($user)
   {
      $this->users[] = $user;
   }

   public function setCategory($userName, $cat)
   {
      for($i = 0; $i < count($this->users); i++)
      {
         if($this->users[$i]->getName() == $userName)
         {
            $this->users[$i]->setCategory($cat);
            return;
         }
      }

      echo "User not found";
   }
}

$angelina = new User("Angelina Jolie");
$brad = new User("Brad Pitt");
$jealous = new User("Jennifer Aniston");

$users = array($angelina, $brad, $jealous);

$userList = new UserList($users);
$userList->setCategory("Jennifer Aniston", "stalker");

 

It's not hard to envision UserList having a method to remove individual users from its internal array, as well.

 

To me, the code I wrote is far more clear than yours.  It deals with concrete entities, each with its own set of properties.  I can mix and match User objects whenever I want without compromising their integrity or the integrity of other components in the system.

 

Something else I just caught: While __construct may be a magic method, its purpose is to set properties and invoke other methods during object creation.  In other words, there's an implied usage expectation when using that method.  The way you're using it is both confusing, as you never intend to use the object that's briefly created, and ultimately pointless, as you don't need a child object there at all.

 

From what I can see, after looking at your code more while slowly waking up this morning, you pretty much miss the point of OOP.  I mean, data encapsulation is a big part of it, yet your class properties are publicly accessible, meaning they can be changed at any time.  You never create any objects (at least none that persist) - what if you wanted several arrays of users, based on their membership levels?  What if users had more info attached to them than their name and membership level?

 

There's a reason why it's termed Object Oriented Programming.

 

 

Thanks for thanking the time mate, but that is a misconception of the whole point!

 

I can lock any class of that anytime, they all belong to the main class USER, its not there, also the point is:

 

the way i use NEW using statics,

They way i do not create $vars (I name then crap loaders) to instantiate classes all the time. Also... i dont like $this-> i love self::

 

and your class does not achieve any closer to what I  return in the 2 sides,  1 User and 2 admin controls information. I don't need FOR on theres. 

Study the sample a little more, check all it really does in all the 3 "subclasses of user" again, user is not present, those manipulate custom  upgrades by specific users and their accoutns, everything set dynamically  thru a panel and forms, and the user, just logs in to see that all happening, samo thing for the admin control.

 

That is all, I dont use $this in my code, my friend was pissed coz i said to me, again to me "matter of choice" personal choice,  I called that oldfashioned in php. Show me things i can never reach by not instantiating a class:

 

$rubbish = class someclass(); i dont need it

I can user interfaces and inside my interfaces refer to all my classes. so many choices.

and internally in my methods i instantiate  all i need using static "when i want static" and self::

 

That is the dilema.  Why New in my code if i use static "class handler" and not instances will never be OO they said.  Also, array sucks in OO they said :)

 

I am not trying to check the eficiency of tha "simple sample".

 

I hope somebody gets it. ( no class instance itself, pls no $this in my code, and new being proper used to call __MagicMethods rather then keep creating foobars() methods when the basics just needed to be loaded. )

 

Im here to learn.

 

Cheers mate,

 

Ops, sorry about all my bad typos, sort of rush moment.

Also look at my class, as if was going to be distributed or always used as a FW.

To start using it, anyone with my API won't ever need to user $vars (eww) to start classes and methodos in their pages.

 

but only:  New comeClass; "do all the pre checks or executions"

and      : comeClass::masteriseWhatIneed($x, $y, $z) " yay here my client will see all the code hint of what to do, when using IDEs such as netBeans".

 

this is another point in the way I code, I also expect myself not using vars all the time.

 

all this in im my sample code:

<?
userUpgrades::setUsrsCond("Mick Doe", "Guest Account");
userUpgrades::setUsrsCond("Allan Doe", "Shopper Discount");
userUpgrades::setUsrsCond("Foo Bar", "Merchant Upgrade");
userUpgrades::setUsrsCond("Madonna", "Merchant Upgrade");
userUpgrades::setUsrsCond("Angelina Jolie", "Guest Account");
?>

Is never typed by hand!

 

my clientes or myself will never need to type, that happens in the all mighty USER class "the one i said its not there" and it is generated when the admin ppl set WHO is gonna get discount today, Whos payed and get account upgraded etc, in their own web interface.

Then, user just logs in, and gets  lets say an ajax "modal box" telling him all that has happened to his account since last operations.

 

And the developers, using this "FW", all they need to do is in a blank php page called userUpgradesInfo.php  that will be displayed in that modal box  right after the login, or by using their "my account control panel" to check things, you know.

<?
new user; // "call the mighty class USER " 
new userUpgrades($_SESSION['mycurrentUser']); // this is the user logged.
?>

The above is all one needs to type to create the accountUpgradesInfo in their system and use the "FW".

 

and on the admin side, any php they set to view in the admin module:

<?
new Admin;  // here
new analiseConditions($_POST) //ajax post thru their Admin panel using a simple input field.
?>

 

PS: IF you get the whole idea you will see that i don't need 3 subclasses there, I created for a quick sample, I am not pasting a whole bunch of source code here. The engine is not the point. Also if attention was payed, you may have noticed that the 3rd class called "analiseConditions" has double  Objects usage and side effects, class USERS and ADMIN "both not there hehe :), but I've made that sample to show that using this referred class to manipulate 2 objetcs won't affect each other, and better, when i call it for lets say USER manipuation, the ADMIN part inside the same class ins't memory loaded, same when I call the static method inside it to manipulate the admin now. But sorry, I am sure all this last were already worked out by yas. Just wanted to clarify.

 

So, don't bother the usage and performance, but the way it's written so others can use it inside their IDEs and no need to keep reading APIs to know what to do to get a simple task accomplished, and please, focus only on the 3 dilemas i proposed.

 

Thank you again blokes. 

 

They way i do not create $vars (I name then crap loaders) to instantiate classes all the time. Also... i dont like $this-> i love self::

That is like saying I don't like bricks so I will build my house with cardboard.

 

Im here to learn.

The fact that you are so defensive of your programming makes it questionable.

 

I assure you that with your method of implementation you will run into problems in the future.

Read the following:

http://socket7.net/article/php-5-static-and-inheritance

There is no real need for instance, and calling them like so:

validate::isEmail($email);
validate::isPhone($phone);

is valid use of OOP in my opinion. As you can see, there are valid cases for all static classes, but I think in some of your cases, you should not being using static classes (more below).

 

Lets entertain the notion that you have a method, in a different class, that wants to use these validation algorithms... How, would you propose, would I be possible to change, say, email validation from the RFC type to a stricter type?

 

Very, very rarely (very possibly never) there's "no real need for an instance".

They way i do not create $vars (I name then crap loaders) to instantiate classes all the time. Also... i dont like $this-> i love self::

That is like saying I don't like bricks so I will build my house with cardboard.

 

Im here to learn.

The fact that you are so defensive of your programming makes it questionable.

 

I assure you that with your method of implementation you will run into problems in the future.

Read the following:

http://socket7.net/article/php-5-static-and-inheritance

 

About the 2 1st statements, no comments.

The last one, great finally you showed something that is in this topic subject and seems like a "barrier" to static methods and properties.

I saw your link, there are work arounds right now and: "PHP 5.3 is right in the corner", __callStatic;

PS:: "I am careless about php 4 and anything older, I follow the upgrades and all the news it brings to us, or the act of number version releases higher is just a hobby? I'm bloody excited about PHP6?"

 

Thanks m8

 

Posted by: rhodesa

this is also a great tutorial on OOP in PHP:

http://devzone.zend.com/node/view/id/638

it's for extreme beginners, but it does a good job at explaining the purpose of OOP

 

Thanx m8, I really appreciate that, your comments and the last one by  448191, are the most constructive so far in my topic Static vs Instance. OOP does not really matter here btw, only a person said that by using static i cannot reach OOP, ever.

 

The link has a great material indeed about OOP!

 

Keep up guys, I want to learn what else I could possibly be missing from php if i don't ever start my classes with instances.

 

"Static Methods VS Instance Methods " Hooah!

 

Cheers,

 

 

There is no real need for instance, and calling them like so:

validate::isEmail($email);
validate::isPhone($phone);

is valid use of OOP in my opinion. As you can see, there are valid cases for all static classes, but I think in some of your cases, you should not being using static classes (more below).

 

Lets entertain the notion that you have a method, in a different class, that wants to use these validation algorithms... How, would you propose, would I be possible to change, say, email validation from the RFC type to a stricter type?

 

Very, very rarely (very possibly never) there's "no real need for an instance".

 

Id fix that notion by calling:

validate::setEmailType($type);
validate::isEmail($email);

or

validate::isEmail($email, $type);

 

Based on my experience in OOP, in all examples that have already read and in all ORM existing, I think that the example provided by Rangel (Reply #3 on: March 04, 2009, 06:15:52 PM) is not 100% OOP.

 

I think impossible to be 100% OOP using only static in all classes.

 

Am I wrong?

 

PHA

Nova Odessa - São Paulo - Brazil

 

Sorry, my English is horrible.

 

Id fix that notion by calling:

validate::setEmailType($type);
validate::isEmail($email);

or

validate::isEmail($email, $type);

 

 

It not only means, as Daniel points out, that ALL your client code breaks, it also means you have to use a conditional in the 'isEmail' method, breaking encapsulation between algorithms and potentially causing unnecessary coupling and duplicate code. Every time you add a new type of validation, you are hacking into code that works. Hacking into code that works is a short route to panic.

 

In your first example, you will also need a static variable to store this flag. This breaks encapsulation, making your application more fragile. In practical terms: sure, you can document, saying you always need the set the flag before using the method. But if at some point you or somebody else forgets to do so, you may not notice this bug until it is forgotten a second time, your application breaks, and you are left scratching your head.

 

I have to be fair and say that there is a way to refactor the above code reasonably:

 

public static function isEmail($string, $type = 'thedefaulttypeyouhavebeenusingsofar')
{
      return EmailValidatorAbstract::factory($type)->validate($string);
}

 

In this way the static 'validate' class becomes a static Facade for hierarchies of validators. But this is a refactoring you can do only once (thus still hardly ideal) without breaking your client code. After that, you will need a proper solution. So if possible, you would probably be better of to that immediately, while the the code is still only sparingly being used.

 

Based on my experience in OOP, in all examples that have already read and in all ORM existing, I think that the example provided by Rangel (Reply #3 on: March 04, 2009, 06:15:52 PM) is not 100% OOP.

 

I think impossible to be 100% OOP using only static in all classes.

 

Am I wrong?

 

PHA

Nova Odessa - São Paulo - Brazil

 

Sorry, my English is horrible.

 

 

Object Oriented code uses objects, not just classes, so no, you're not wrong, in fact it is not Object Oriented at all (0%). But I don't think that is the discussion here. People not used to OOP often fail to see the use of it until they have experienced some of it's benefits first hand (I'll see it when I believe it kind of thing). Can't blame them, as it is not always as easy to understand, let alone explain without resorting to terms for other concepts not fully grasped yet.

 

In short, you can't expect to be explained the usefulness of OO fully in a single forum thread. Many very smart people needed many books to do so. All we can do is give you some examples and beg of you to trust our advice, at least enough not to discard it and give OO a proper chance.

The biggest problem is that people fail to see that object oriented programming is an entirely different paradigm than imperative programming. It's not possible to do a 1:1 conversion on every single line to convert an imperatively written program to an object oriented program. In most cases it would constitute an entire rewrite.

Awesome, this is getting really educative now :) great answer m8s!

Ok let me put it all one step forward:

It not only means, as Daniel points out, that ALL your client code breaks, it also means you have to use a conditional in the 'isEmail' method, breaking encapsulation between algorithms and potentially causing unnecessary coupling and duplicate code. Every time you add a new type of validation, you are hacking into code that works.

 

This way I trully see what you guys mean above:

validate::isEmail($email, $type);

 

But in this way, I still don't see breaks or hacks, the conditional "static method" is there, part of the class, but it will be only called or placed on top of the e-mail, when the dev using such "fw" wants to add extra validation feature for e-mail before the email goes to the next step. I'd say, use it, or call such methods as you go. Is this a hack?

validate::setEmailType($type);//Call this bloke to increase the e-mail features when needed only.
validate::isEmail($email);

 

 

Based on my experience in OOP, in all examples that have already read and in all ORM existing, I think that the example provided by Rangel (Reply #3 on: March 04, 2009, 06:15:52 PM) is not 100% OOP.

By the way this is my mate and the one responsible to make me start all this :)

 

Okies, lemme dive in the swamp stuffed with crocodiles :) "PS: naked at all!"

The OOP I do agree is far complex to make any statement coz it totally depends on the programming Design and Patterns you are going to apply to your job.

Knowing that Id ask:

Why am I not dealing with objects "Ops, I'll use singular here, {object, explains below}":

userUpgrades::setUsrsCond("Mick Doe", "Guest Account");
userUpgrades::setUsrsCond("Allan Doe", "Shopper Discount");

Aren't I dealing with my Object USERS, that has UserUpgrades features that has UserConditons? All this so supply my Users needs?

 

I've made it singular coz "no 1 pointed me this when i asked":

I want to learn what else I could possibly be missing from php if i don't ever start my classes with instances?

 

One thing i cannot do "now, and without strong hacks" coz in php 5.3 it's over and I will do with Late Static Binds

Follow the comments.

 

$Obj1 = new car();
$Obj2 = new car();

$Obj1 = setCarColour("blue");
$Obj2 = setCarColour("red");

$Obj1 = getCarColour(); // cool its Blue, no overrides! lo jus as expected.

 

But by using statics:

new car; // Normal, I have things to be constructed.
new car; // STUPID, overriding the construct method isn't helping

car::setCarColour("blue"); // Great, car is now bluewish!
car::setCarColour("red"); // STUPID, you just repainted over! I hate red ya moron!

car::getCarColour(); //OMG I've payed for blue why do I bloody get a RED one???

Weird, I've heard ppl sayen static method cannot, be overriden, well it can, and will.

 

BUT!!!

 

new car; 
car::setCarColour("blue"); 
car::getCarColour();

new car; 
car::setCarColour("red"); 
car::getCarColour(); 

 

Great! I now have the 2 car colours as I've expected and using static, safely stored in my DB, or session!

What I do not have?

Well by the fact ppl say I am not Object Oriented, I just don't have my $OBJ1 and $OBJ2 vars alocated in memory to play with.

 

Conclusion:

 

I know, I so know all the flexibility I have to use the instance method and then play with my methods as it was a salad, call it anytime and in any order i want, but the only thing that really twists my "bollocks" and makes me feel ....well ya know... Is the fact ppl say Static is NOT OOP.

 

Ok, now lemme swim faster, crocodiles in plain sight and I must get out real fast from this OOP swamp I've dove in!!! run forest... ops I mean... swim Forest..swim... :)

 

Thx m8s :)

 

Well, the thing is that it's not "wrong", at least not syntactically. It's just not OOP. In OOP you can put an emphasis on the second "O" (oriented), that is, the code revolves around objects and their interaction with each other, it's object oriented.

Brillant Daniel, that is more than correct, because like i said, the way i see Object is fundamented is to be that $var, storing the class, methods and consequently properties. That understood and following the lack of Late Binds to use right now (as of PHP 5.3) what if:

new car("Obj1"); 
new car("Obj2"); 
car::setCarColour("Obj1","blue"); 

car::getCarColour("Obj2");
car::getCarColour("Obj1");

new car("Obj3"); 
car::paintArgument2as1("obj1","obj2");
car::paintArgument2as1("obj3","obj2");

 

Why this? well I am still using statics, not using var instances because, runtime is not enough (I have more reasons), so I encapsulate my Objects in the class, now lasting thu my entire session, or perhaps, lets make it stronger: tmp db table for the obj CAR that lasts, hmm let's say, untill admin decides so?

 

Didn't the static reached the "Oriented" now?

 

 

Agreed mate 448191,  $GLOBALS is another option to instantiate objets.

I've considered a certain level of agreement about the static theory I am suggesting here by adding 1 more extra option  “$GLOBALS in my last example, where I explicitly demonstrated how you can achieve 100% OOP by using static methods rather than instance object in your programming design, the same post I've left a question remarking the “oriented” which I understood it was the last part missing to bring it all to a common sense that in fact, no! static will NOT drive you away from OOP. I will grant myself the freedom to once again move another step ahead in this thread.

Although this time with no fear of those wandering crocodiles from the swamp called OOP, the one that many raise excitement to jump in, but not many hold breath enough to reach the crystal clear water found  right after a long and deep dive, conceived of experiments that will safely lead you away from all the scary creatures and legends left in the shallows by those that tend to follow the crowd and its tendencies, usually reporting what was told to or perhaps what was read somewhere else. Yes,  that is right, I've said read somewhere. What? Am I being insolent? Perhaps you envisioned I am referring  that books and methodologies out there can possibly be wrong? No, I would not dare, I am suggesting you to believe in your own experiments, give yourself credit and confidence enough to expose your theories based upon your practises.

At last so many argument and expect evidence before they believe or agree with the only book men may call holly. That being said, it is not the matter of who's wrong or right but the manner we accept new theories.

Ok, if you have not fallen asleep yet I will expose mine:

Earlier I was noticed  to be so defensive about my way of “programming”, nope not the way and not the programming at all, but from now on you may call me “Mr Static Methods OOP Theory”.

That is right, I am the one that seems to be swimming opposite to the flow, running against the crowd and dressing black when the fashion says yellow, let's think then:

 

1.If one uses any search engine, buy books or whatsoever to learn about OOP certainly will find:

 

-  Object => “The thing{data types, classes, methods and properties} stored in an allocated space”.

-  Instance => “The name given to the variable that will access the object stored in the allocated space”.

 

2.Things that most will not emphasise and where the misconception begins:

 

- It does not specify one must use only local (runtime) variable to instantiate the object.

- It does not specify one cannot use $GLOBALS (superglobal array) to reference the object.

- It does not specify one cannot use a static variable to reference the object.

- It does not specify one cannot use $_SESSION either.

As long as the Object is allocated in a region of storage and offers a way to access it by reference, it is an Object but It does not specify that the memory allocation must be stack, heap or static in the RAM or even SSD and HDD allocation. This can be analysed, discussed and decided by read and write performance among all methods, besides it's beyond this topic one thing I assure, RAM or solid state memory it will allocate data types anyway. 

 

Definition:

 

Anywhere you may search, it might bring snippets, samples and tutorials always using the “classic, standardised and easiest way” to reference objects:

Instance of Object using local variable at runtime.

 

So my final theory definition is:

Independently of the allocation method if you maintain interaction with message passing, inheritance and re usability of the Object, then you are in the right path on Object Oriented Programming.

Following the above I say, YES you can have a 100% OOP even if you are using only static methods, without runtime instantiation and strongly using class-based-programming in your application.

Neither the array usage will downgrade the application to a non OOP style, the opposite, by using using class methods to build and manipulate 2d or 3d arrays seems to bring more performance and dynamism. You can add data type, retrieve, edit or remove all in Object Oriented manner and this applies not just to an array but also $GLOBALS or even $_SESSION .   

 

Conclusion:

I believe that is not needed to mislead the concept of OOP,  to confuse Object with Object Oriented and  not even call it a Static vs Instance war, but realise that when it comes about programming we must not forget the logic and its possibilities to quite often achieve different ways to solve 1 single issue.

I just wanted to point a different usability for what is already included in the php core code. I am not telling you to only use instances “the old way” like I told my friend, or the “new way” using only statics nor a mix of both, each case is a case. You decide, benchmark it, run performance analyses, use your developer's vision to work with new concepts and experiments, run trials and the most important, ideas and information exchange just like is happening here leads us all to enrich our applications and degree of knowledge.

 

Awesome community here btw!

 

Cheers mates.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.