Welcome Guest, Not a member yet? Register   Sign In
Objects: Why are they useful?
#11

[eluser]Beren[/eluser]
[quote author="codex" date="1201063122"]Ucant & Wired:

I (think I) understand the concept of objects a bit better. You have a class called Animal, and in this class all functions that make an animal an animal are described. You can create instances of the animal class (objects) to create dog, cat etc etc and have all those properties available. Right? If right I understand ;-)[/quote]

No not entirely, you have a class Animal (that might do things like eat, move etc) and then you would have further classes 'inherited' from that like Cat (does things like meow, purr) and Dog (bark and fetch_ball). Instances are specific cats or dogs, so Fido is an 'instance' of the 'class' Dog (which is a type of class extended from Animal). Likewise Garfield is an instance of a Cat class. An instance is a single 'thing' of a specific 'class'. See?
#12

[eluser]tonanbarbarian[/eluser]
I certainly agree with ucantblamem - he often explains things better than i do that is why he does more training of clients than i do
and I also agree with Beren that using Object Oriented Design or Programming does after a while get you into a mindset that helps you to code better because you start to treat each object as discrete.
In fact I credit Objects with a change in the way I programmed so that now I try to create objects that are fairly generic but can be extended to do very specific things as well

And that brings us to the other thing about objects not really talked about yet - extending

Lets take ucantblamem's hammer example. This object might be fine to explain a regular carpentry hammer but what if we need a slegde hammer
Well we can extend the hammer definition and just add the things we need that it doesnt have

Code:
class Sledge Extend Hammer {
    var $weight = 15;
    
    function Sledge($material = 'metal', $weight = 1) {
        parent::Hammer($material, $weight);
    }
    
    function demolish() {
        // Do funcationality here
    }
}

And it now inherits all of the properties and methods of hammer but has its own extras that can be very specific.
So now I know the Sledge Hammer weighs more than the regular hammer and not only can it be used to hammer_nails and remove_nail (not a good example i guess) but it can be used to demolish as well

As for the question about what use is result_object.... not much in its current version
I have seen other version of this implements (in Mambo/Joomla) that will take an existing object and add the properties to it. This can now be done in PHP5+ by passing extra parameters.
If CI result_object could do this it would be more useful, but in general I think I just prefer to use arrays of data from the database. If the object does not have any methods to use I do not think it has much use as such.
#13

[eluser]ejangi[/eluser]
@Codex - pretty much spot on. I (like thurting) also recommend books. Honestly, there's only so much you can learn from quick tutorials and manuals online. I used to hate reading and now I have quite a large library of technical titles on my shelf. ;-)
#14

[eluser]codex[/eluser]
[quote author="ucantblamem" date="1201063963"]@Codex - pretty much spot on. I (like thurting) also recommend books. Honestly, there's only so much you can learn from quick tutorials and manuals online. I used to hate reading and now I have quite a large library of technical titles on my shelf. ;-)[/quote]

Yeah, it's not that I don't want to read books on OOP, it's just that while in the store I found books that were too complicated for my taste. I basically wanted something like 'OOP for dummies'.

It was also beacuse of this post http://ellislab.com/forums/viewthread/69407/ that I started to wonder about objects vs arrays.

@ Thurting: I wasn't offended by you saying I should read books. It was more the way you said it. But there was no harm done. We're still friends ;-)

@ All: Thanks for your explanations. I appreciate it. Though the basic concept was sort of clear to me, it was this I needed to fully understand. Thanks!!
#15

[eluser]wiredesignz[/eluser]
Quote:As for the question about what use is result_object.... not much in its current version
I have seen other version of this implements (in Mambo/Joomla) that will take an existing object and add the properties to it. This can now be done in PHP5+ by passing extra parameters.
If CI result_object could do this it would be more useful, but in general I think I just prefer to use arrays of data from the database. If the object does not have any methods to use I do not think it has much use as such.

PHP4 Objects can have properties and functions added programtically also. Therefore PHP4 can extend a $query_row() object.
#16

[eluser]Edemilson Lima[/eluser]
Back to 2001, I didn't realize how useful objects are since I started to code multiples calls to different databases without them. Before, I must setup a lot of variables for the same things:

Code:
$host1='localhost';
$user1='mydbuser';
$pass1='mydbpass';
$base1='mybase';
$host2='192.168.1.100';
$user2='otherdbuser';
$pass2='otherdbpass';
$base2='otherbase';

$link1=mysql_connect($host1,$user1,$pass1);
if($link1) {
  mysql_select_db($base1,$link1);
  $query1="select * from table1";
  $result1=mysql_query($query1,$link1);
  if(mysql_num_rows($result1)) {
    $link2=mysql_connect($host2,$user2,$pass2);
    mysql_select_db($base2,$link2);
    if($link2) {
      while($row1=mysql_fetch_array($result1)) {
        $query2="update table2 set field='value' where id='$row1->[id]'";
        mysql_query($query2,$link2);
      }
    }
  }
}

Well, we can simplify a little bit the code above with functions, but after I have made my "database" class, look how the mess above become:

Code:
$db1=new database($host1,$user1,$pass1,$base1);
$db2=new database($host2,$user2,$pass2,$base2);
$db1->db_query("select * from table1");
if($db1->db_rows()) {
  while($db1->db_fetch()) {
    $db2->db_query("update table2 set field='value' where id='$db1->[id]'");
  }
}

As you can see, is much simpler do the things with objects and we can focus on what really matters: the application logic. And also, the database class can check if the connection was made before or not and connects automatically. It can create tables, benchmark the queries, send database errors by Email, check if a table exist, use data compression for remote server connections (MYSQL_CLIENT_COMPRESS), count the number of rows returned by a query, store the last id generated, store the number of rows that was affected, format returned data, free results, repair tables, etc, etc. The functions works together and exchange data nicely, preventing errors and making the appropriate checks. Thanks to the objects properties and methods, all of this is possible. And the best of all, you only write it once and spawn how many objects from it you need.
#17

[eluser]Nick Husher[/eluser]
Quote:It was also beacuse of this post http://ellislab.com/forums/viewthread/69407/ that I started to wonder about objects vs arrays.

One thing that PHP (and Javascript, and many 'scripting' languages) have that other, more-traditional languages have is that they can create complex associative data structures on the fly. In Java and C++, it's difficult and unwieldy to build a data structure that contains multiple nested properties and it doesn't buy you much in the way of expressivity.

So with PHP, it's not always useful to build a complex object structure; it just takes a long time without buying you any elegance.
#18

[eluser]ejangi[/eluser]
I really do wish PHP had a short-hand method of building objects. JavaScript has JSON and Ruby has Hashes. I can't think of the number of times I wish I could just write something like:

Code:
{
    title: 'Hello world',
    description: 'I cannot think of anything right now',
    parent: {
        title: 'It is great to be alive',
        description: 'I love descriptions'
    }
}

And have PHP turn that into objects. *sigh* One day... One day... Tongue

[EDIT:] And yes, I know there's YAML and JSON parsers for PHP, but that's not what I want. I want native support (built into the language) for some kind of object shorthand notation. ;-)
#19

[eluser]tonanbarbarian[/eluser]
[quote author="wiredesignz" date="1201064762"]
PHP4 Objects can have properties and functions added programtically also. Therefore PHP4 can extend a $query_row() object.[/quote]

Yes that is true
However the $query->result_object() in CI does not let you pass the initial object to be extended.
If you wanted the result_object to return an array of a particular class that was created and you just wanted it to set the properties of that object it would not be able to do it.

Having said that, in PHP 4 at least (not sure about PHP5) it is slow to programatically add properties to an existing object. I can only assume adding methods is slow as well.

for example if you have an existing class definition like this
Code:
class Something {
  var $foo = null;
} // class Something
then we instantiate it
Code:
$obj = new Something();
Assigning a value to the property fo is fine because it is already declared
Code:
$obj->foo = 123;
But if we assign a value to a property that does not yet exist this is relatively slow
Code:
$obj->bar = 456;
I believe this is because PHP has to redeclare the object in memory to add this property

As Nick says this is a great feature that allows a lot of flexibility that you just cannot do in some other OO languages, however if you want everything to run fast avoid creating new properties on objects if you can help it

That also means avoid using stdClass, because then every property you add to it has to be redeclared.
In fact if you are considering using stdClass you should think about using an array instead.

stdClass, for those that do not know, is a way of create a new object as an empty class
Code:
$obj = new stdClass();
$obj->foo=123;
$obj->bar=456;

Not 100% sure but the trick here, if you really need to create an empty class and then assign properties to it, this method might be quicker
Code:
$obj = array();
$obj['foo']=123;
$obj['bar']=456;
$obj = (object)$obj;

So the idea here is to create an array first and assign items to to, because array processing is quick
then cast it to an object and you have an object with the properties you want and hopefully it has done it quicker than the previous method. (One day when I get some time I might check if this is really quicker or not)
#20

[eluser]Edemilson Lima[/eluser]
Upcoming changes in PHP 6.0: (from http://www.phpbuilder.com/columns/ian_gi...51206.php3)

PHP 6.0 looks to be an exciting release. Nothing is absolutely fixed yet, but it looks like it will see the demise of three of my pet peeves: register_globals, magic_quotes_gpc and safe_mode. The first was just a big security hole, the second messed with the data and made changing environments potentially nightmarish, while the third was a misnomer that nobody really understood, and provided a false sense of security. There's also quite a lot of work scheduled to do with Unicode. Here are some of the changes:

* The register_globals, safe_mode and the various magic quotes options will be removed.
* The ereg extension is removed, while the XMLReader, XMLWriter and Fileinfo extensions are added to the core, and by default are on.
* Another addition I find particularly exciting is that APC (Alternative PHP Cache) will be added to the core, though will be off by default. APC can provide serious performance benefits.
* All E_STRICT messages will be merged into E_ALL, another positive change that will encourage good programming practice.
* ASP style <% tags will no longer be supported.
* Addition of a new 64-bit integers. The current integer type remains as is, 32 or 64-bit dependent on the platform.
* Use of foreach with multi-dimensional arrays, for example foreach($array as $k => list($a, $b)).
* A new switch in php.ini will allow you to disable Unicode semantics (by default they will be on).
* There will also be various string improvements related to Unicode.
* The microtime() function will return the full floating point number, rather than microseconds unix_timestamp, as at present, probably making the function more readily useful for most people.
* The {} notation for string indexes will no longer be supported, while the [] version will get added substr() and array_slice() functionality. Previously [] was deprecated, but most developers, including myself, seem to use [].
* FastCGI will always be enabled for the CGI SAPI, and will not be able to be disabled.
* The ancient HTTP_*_VARS globals will no longer be supported. Everyone should have had more than enough time to remove any traces of these.
* var will alias public. var was permitted with PHP4 classes, but in PHP 5 this raised a warning. In PHP 6 var will simply be an alias for public, so no warning is necessary.
* The ze1 compatibility mode, which tried to retain PHP 4 behaviour but had some bugs, will be removed.
* Dynamic functions will no longer be permitted to be called with static syntax.

More info about it here: http://www.corephp.co.uk/archives/19-Pre...PHP-6.html




Theme © iAndrew 2016 - Forum software by © MyBB