Jump to content

Problems understanding some Object Orientated PHP


j.smith1981

Recommended Posts

I am struggling to understand certain aspects of PHP with regards to Object Orientated Programming.

 

When would you need to make a constructor and when would you not? Thats one of the biggest things I am finding most confusing.

 

Whats the difference with echo and return? I mean I know return wouldnt output to a webpage, but what is the purpose of return then, over something like echo?

 

Just a bit confused about that to be honest, really getting to grips with this concept though apart from those 2 aspects for the moment.

 

Jeremy

Link to comment
Share on other sites

Every class has a constructor, even if you don't define it. There's always a default constructor, that does nothing.

 

The purpose of return is to return a value from a function. In majority of cases, functions aren't required to display anything, but instead we're interested in the results.

Take in_array for example. It's one of the PHP core functions, that check if an element is present in array. You wouldn't like it to echo 'YES' or 'NO' to browser, because that would be pretty useless. Instead, this function returns a boolean true or false values, so that you can use it in as a condition in if()

 

if(in_array($element,$someArray)) {
  //do something
} else {
  //do something else
}

Link to comment
Share on other sites

Every class has a constructor, even if you don't define it. There's always a default constructor, that does nothing.

 

The purpose of return is to return a value from a function. In majority of cases, functions aren't required to display anything, but instead we're interested in the results.

Take in_array for example. It's one of the PHP core functions, that check if an element is present in array. You wouldn't like it to echo 'YES' or 'NO' to browser, because that would be pretty useless. Instead, this function returns a boolean true or false values, so that you can use it in as a condition in if()

 

if(in_array($element,$someArray)) {
  //do something
} else {
  //do something else
}

 

So you would pass that to some kind of constructor then or something to actually output it then?

 

Sorry just finding this quite confusing (good though discapline though to do OOP I am gathering bits of information myself just goint to take some getting my head around), I did Java in OOP when I was at University, but I find PHP quite confusing, if I went back to Java I think I would find it much easier to remember what I was originally doing.

 

But with constructors, without one there wouldnt be a point in the application, what confused me about that was, a post on some other blog I was looking at explain that user input from a standard HTML form would not need a constructor hmm bit confusing.

 

Interesting though,

Jeremy.

Link to comment
Share on other sites

You might be confused, because in Java you need to define main class for application and implement public static void main(String [] args) method, which will be called when application is executed. In PHP it is not necessary. Application starts right after <?php tag.

 

Link to comment
Share on other sites

It is really interesting though, think I just need to really study this paradigm closely.

 

I mean I do get what it does and allows you to do, the benefits of doing object orientated programming, allows you to use reusable code, add in functionality without (or at least should allow for extra functionality without) affecting the rest of the code.

 

Can see why it benefits since I have had to do this multiple times in just VBA (which I am starting to really hate, since everytime I make a change I have to rejig everything and the programs I am doing with excel are getting quite big.

 

I am even attempting to do this in C# preferably, but with the added trouble of using an xls file with a CSV file and using the xls file as a database sort of.

 

Its cool that programming now is really making sense, getting a grounding in C++ and to be honest I love it, doing that kind of advanced programming, its all good!

Link to comment
Share on other sites

If you want to learn C#, do yourself a favor and download Visual Studio 2010 Express.  It's a free IDE from Microsoft that has a built-in database server.  In addition, get yourself a copy of C# 4.0 In A Nutshell from O'Reilly Press.

 

Now, to your questions...

 

A constructor is not the start of a program/app, but rather the mechanism that creates objects.  The basic analogy is that a class is a blueprint, an an object is an individual thing made to the specifications of that blueprint.  The constructor is the middle man - it's what actually builds the object.  The assembly line.  Like Mchl said, whether or not you define a custom constructor is irrelevant.  A constructor is ALWAYS invoked when a new object is made.  Custom constructors are often necessary as they allow us to control the default state of a new object by giving us a place to run our own initialization code and to populate data members dynamically.

 

Return and echo are two different beasts entirely.  Echo merely spits output to the screen.  Return is more useful as it allows us to retrieve the value generated by a function to use in other code.  Return is necessary due to scope - values generated within a function are not accessible to the code that invoked the function unless they are returned (exception made for arguments passed by reference, but that's another discussion entirely). 

 

PHP is a little different than the other languages you're familiar with in that function signatures have no visible return type, and the types for arguments are optional, and often not used.  Despite these visible differences, you can (and most likely should) treat PHP functions as though they do have a particular return type (void is legitimate) and argument types.  It'll made your transition smoother.

Link to comment
Share on other sites

If you want to learn C#, do yourself a favor and download Visual Studio 2010 Express.  It's a free IDE from Microsoft that has a built-in database server.  In addition, get yourself a copy of C# 4.0 In A Nutshell from O'Reilly Press.

 

Now, to your questions...

 

A constructor is not the start of a program/app, but rather the mechanism that creates objects.  The basic analogy is that a class is a blueprint, an an object is an individual thing made to the specifications of that blueprint.  The constructor is the middle man - it's what actually builds the object.  The assembly line.  Like Mchl said, whether or not you define a custom constructor is irrelevant.  A constructor is ALWAYS invoked when a new object is made.  Custom constructors are often necessary as they allow us to control the default state of a new object by giving us a place to run our own initialization code and to populate data members dynamically.

 

Return and echo are two different beasts entirely.  Echo merely spits output to the screen.  Return is more useful as it allows us to retrieve the value generated by a function to use in other code.  Return is necessary due to scope - values generated within a function are not accessible to the code that invoked the function unless they are returned (exception made for arguments passed by reference, but that's another discussion entirely). 

 

PHP is a little different than the other languages you're familiar with in that function signatures have no visible return type, and the types for arguments are optional, and often not used.  Despite these visible differences, you can (and most likely should) treat PHP functions as though they do have a particular return type (void is legitimate) and argument types.  It'll made your transition smoother.

 

Ahh I got that by going through some examples of constructors, its just I failed the exam for Java at University, but its starting to make sense now in the workplace at least.

 

I went through the difference between return and echo, its just when I was developing in the X Cart system, I thought return was like echo in the way that it outputted a product image, which lead me to believe that is was like echo, but its not now and I am fully aware of what its meant for now, really as I understand it, return simply yea sends a value back to the part of the program that called that function, thats how I understand what its meant for.

 

Good to know though, thanks again ever so much for your explanations I really appreciate it!

 

Jeremy.

Link to comment
Share on other sites

  • 2 weeks later...

I think I am finally getting this sussed now!

 

I'd love you to critique this script in php its meant to be calling display but there's an error on line 17, can someone help me please?

 

Would be a great learning curve, copied and understood from my PHP6 and MySQL bible (maybe its only meant for v6 and I am actually running 5 but I think this should still work for v5, can someone confirm?)

 

<?php
class MyClass {

public $var1 = 'This is var 1';
public $var2 = 'This is var 2'; // Leave these blank variables for now!

function display() {
	if(isset($var1)) { // if var1 contants data then display that or if it is not set, which it isnt the display the other var2
		echo $this->var1;
	} else if(!isset($var1)) {
		echo $this->var2;
	} // these above wont display as we havent created an instance of this class yet, we're just creating a class with functionality!
}

// to accomplish output we need to create an instance of MyClass and then call a function/otherwise known as a constructor!

$myNewClass = new MyClass; // Creates an instance of this class
$myNewClass->var1; // Creates a pointer to var1
$myNewClass->var2; // same as previous pointer but then construct myNewClass var2
$myNewClass->display(); // class display function above

}
?>

 

Again any helps much appreciated in advance!

 

Thanks again and I look forward to any replies,

Jez.

Link to comment
Share on other sites

Hate to tell you this, but you're not on the right track.  At all.

 

First of all, pointers don't exist in PHP.  Whatever it is you think you're doing, well, you're not.  The '->' operator is akin to the '.' in other languages.  $object->member in PHP is the same as object.member in other languages (Java, JavaScript, C#, etc.).  So, you're not creating a pointer to anything when you use the arrow. 

 

Second, merely invoking an object's data member does nothing more than return the value of that member.  $myNewClass->var1 merely returns the value of var1.  Since you don't assign that value to another variable, or use it in another way, it's a useless statement.  The same thing goes for the $myNewClass->var2 statement.  It doesn't do anything.  You're not constructing new objects.  You're only accessing the guts of the one and only object you DID construct - $myNewClass.

 

You imply that this code came from a book on PHP 6.  You've been scammed.  PHP 6 isn't even out yet.  AFAIK, there isn't even an ETA on its release.  Some of the proposed features have been placed in new versions of PHP 5 (I think the latest version is 5.3.2),  Get yourself a good book on OOP for PHP - PHP Objects, Patterns, and Practice by Matt Zandstra.  And, stay away from anything mentioning PHP 6.  It's snake oil.

Link to comment
Share on other sites

You imply that this code came from a book on PHP 6.  You've been scammed.  PHP 6 isn't even out yet.  AFAIK, there isn't even an ETA on its release.  Some of the proposed features have been placed in new versions of PHP 5 (I think the latest version is 5.3.2),  Get yourself a good book on OOP for PHP - PHP Objects, Patterns, and Practice by Matt Zandstra.  And, stay away from anything mentioning PHP 6.  It's snake oil.

 

Well said.

 

There's been books around for PHP6 for 2 years. Its just publishers & authors trying to cash in by selling a 'new' book.

Link to comment
Share on other sites

Did you even try to run this code? It's invalid and should not run at all.

 

Oh right ok thats fair enough gonna stay away from that then, how can they actually do this legally then?

 

Should not be allowed I think.

 

Thanks for the heads up though, wont continue to use that then, went off some tutorials sometimes though off the web, I mean from what I have been learning from some sitepoint work, I looked at, it seems to be making sense, thanks allot for that!

 

Jez.

 

PS Thanks for such a speedy reply, I thought something was a bit suss about that, thanks for confirming it though, its just I thought since they might know something about it, but if its merely a way of trying to sell books, I'll keep what you said in mind from now on. I am running a very old version of PHP myself v5.1.6 with centos 4 so its quite old but dont have a computer to run anything more than that version of centos sadly.

Link to comment
Share on other sites

Your example could be reworked to this:

 

<?php
class MyClass {
  public $var1;
  public $var2;
  
  public function display() {
    if(isset($this->var1)) { // if var1 contains data then display that or if it is not set, then display the other var2
      echo $this->var1;
    } else if(isset($this->var2)) {
      echo $this->var2;
    } else {
      echo 'No instance variables were set';
    }
  }
}	
$myNewClass = new MyClass; // Creates an instance of this class
$myNewClass->display(); 

$myNewClass->var2 = 'contents of $myNewClass->var2';	
$myNewClass->display(); 

$myNewClass->var1 = 'contents of $myNewClass->var1';	
$myNewClass->display(); 

Link to comment
Share on other sites

Woops sorry my mistake it says it is error prone I thought this book was ok actually I mean I use it every now and again just to remember certain things though thats all as it says PHP6 (albeit allegedly pml), but then it does it its error prone (which it evidently is but then it creates a much better solution in the next little bit.

 

Gonna try getting my head around that, when I have sussed it, can I review this with you?

 

Thanks ever so much for your help so far, I am finding this quite exciting to be fair, of course its not a constructor, thats the __construct isnt it? Or something like that anyways, am I going down the right lines now?

 

Thanks again for all your help though, much appreciated!

 

Jez

Link to comment
Share on other sites

Hmmm, I hope you don't take this the wrong way, but it seems kind of like you need to just forget everything you know about OOP, get a good book, and read a large part of it.

 

Actually, how long have you been coding?  Because if you've been coding like 3 days, it might be easier to avoid OOP for a while and get a good grasp on procedural programming.  Just an opinion that procedural is easier though, since I would imagine some people find OOP easier.

Link to comment
Share on other sites

Hmmm, I hope you don't take this the wrong way, but it seems kind of like you need to just forget everything you know about OOP, get a good book, and read a large part of it.

 

Actually, how long have you been coding?  Because if you've been coding like 3 days, it might be easier to avoid OOP for a while and get a good grasp on procedural programming.  Just an opinion that procedural is easier though, since I would imagine some people find OOP easier.

 

Oh noo of course I wouldnt take that the wrong way!

 

I am finding this very challenging but eager to nail it spot on eventually with some help, thanks for your continued feedback though I didnt expect replies as rapidly about that.

 

Its like when I tried making a DNS server, grr that took me 2 years to sort out, but I did get it eventually and allowed me to understand how the Internet works, I am sure with a bit of determination (I never lack that), I will nail this and will become fluent.

 

To be honest I really want to aswell, seen allot of freelance work out there that you must be OOP capable so to speak and be able to write clean comprehensible code etc, you know?

 

Thanks for your feedback (feel a little embarrased I didnt put isset then $this-> and then the variable, grrr *bangs head against wall* lol.

 

Kind regards as always,

Jez.

Link to comment
Share on other sites

I have been looking at this link:

 

http://phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html#2

 

I am going to nail this even if it kills me lol.

 

I am going in the right way arent I?

 

Just wanted to make sure I was going on the right route, once I have many other different occurences of OOP with PHP i'll find it easier I think, its just seeing different examples etc that allows me to think of better ways to write my code.

 

Just done the class and methods, I then add in the data once an object has been initiated isnt it?

 

Sorry if thats a rubbish explanation but i was doing something like adding the data in at the top wasnt I? not how its supposed to work correct?

 

Any feedbacks greatly appreciated,

Jez.

Link to comment
Share on other sites

Its not exactly a ground breaking tutorial but I suppose it describes some basics. Your not really going to get your head around OOP until you start to learn and implement well known design patterns.

 

I'm sure however if you've already programmed in Java and C# you should be aware of this. OOP isn't language specific, the patterns remain the same no matter what language your using.

Link to comment
Share on other sites

Its not exactly a ground breaking tutorial but I suppose it describes some basics. Your not really going to get your head around OOP until you start to learn and implement well known design patterns.

 

I'm sure however if you've already programmed in Java and C# you should be aware of this. OOP isn't language specific, the patterns remain the same no matter what language your using.

 

I now that yes, that OOP is more a standard that cuts across allot of programming languages, what I have never understood is exactly how to get past the constructor stage thats what my real problem was.

 

I know it was not ground breaking but I can see how that would work in developing bigger solutions and I am wanting to start developing just for the fun of it, my own forum, just to see if I can do it in OOP and maybe invent things for it that has probably been done before and progress like that.

 

I am never the one to be defeated, what I didnt want to do was to look at that and not try it myself, could you critic my own code for me? Dont want to go on until someone helps me with this, just when you can though:

 

<?php

class MyClass {

public $myvar1;
public $myvar2;

function display() {
	echo $this->myvar1;
	echo $this->myvar2;
}
}

$myNewClass = new MyClass;
$myNewClass->myvar1 = 25;
$myNewClass->myvar2 = 30;

$myNewClass->display(); // call the function

?>

 

I know again its barely ground breaking (well its not lol), but its allowed me to learn something I've wanted to get my head around for ages to be perfectly honest with you.

 

Any advice back is greatly appreciated and thank you,

Jez

Link to comment
Share on other sites

Its not exactly a ground breaking tutorial but I suppose it describes some basics. Your not really going to get your head around OOP until you start to learn and implement well known design patterns.

 

I'm sure however if you've already programmed in Java and C# you should be aware of this. OOP isn't language specific, the patterns remain the same no matter what language your using.

 

I now that yes, that OOP is more a standard that cuts across allot of programming languages, what I have never understood is exactly how to get past the constructor stage thats what my real problem was.

 

I know it was not ground breaking but I can see how that would work in developing bigger solutions and I am wanting to start developing just for the fun of it, my own forum, just to see if I can do it in OOP and maybe invent things for it that has probably been done before and progress like that.

 

I am never the one to be defeated, what I didnt want to do was to look at that and not try it myself, could you critic my own code for me? Dont want to go on until someone helps me with this, just when you can though:

 

<?php

class MyClass {

public $myvar1;
public $myvar2;

function display() {
	echo $this->myvar1;
	echo $this->myvar2;
}
}

$myNewClass = new MyClass;
$myNewClass->myvar1 = 25;
$myNewClass->myvar2 = 30;

$myNewClass->display(); // call the function

?>

 

I know again its barely ground breaking (well its not lol), but its allowed me to learn something I've wanted to get my head around for ages to be perfectly honest with you.

 

Any advice back is greatly appreciated and thank you,

Jez

 

God I am silly sometimes should have said, where is the best place to put the output in?

 

I know this is not the best scenario in anycase but would just be good to look back to on a very primative example about OOP, any thoughts?

 

Really any replies would really help benefit my understanding of OOP, I dont mind you can critique my code to death (thats why I posed to have it criticised, I appreciate I am rubbish at OOP at the moment but want to become an efficient coder in the future).

 

Thanks ever so much for reading,

Jez.

Link to comment
Share on other sites

There's not much to criticise here. It's a simple class you see often in tutorials.

In actual programming you most often declare fields private and access them through public getters and setters methods.

 

Also it's usually a good idea to  separate data presentation (displaying) from business logic. For example like this.

 

<?php
/** 
* This class responsiblity is to implement some business logic
*/
class MyClass {
  /** 
   * myvar field
   */
  private $myvar;


  /** 
   * Setter method for myvar field
   */
  public function setMyvar($v) {
    $this->myvar = $v;
  }

  /** 
   * Getter method for myvar field
   */
  public function getMyvar() {
    return $this->myvar;
  }
}

/** 
* This class responsibility is to display results
*/
class MyDisplayer {

  public function display(MyClass $myObj) {
    $v = $myObj->getMyvar();
    echo "myvar = $v";
  }
}

 

These two classes would work together like this:

 

$obj1 = new MyClass();
$obj1->setMyvar('object1');

$displayer = new MyDisplayer();

$displayer->display($obj1);

// you can now create another instance of class MyClass, and use $displayer to display it's content

$obj2 = new MyClass();
$obj2->setMyvar('object2');

$displayer->display($obj2);

 

This example is intentionally a bit oversimplified, but it should show you, that the power of OOP lies in cooperation between objects of different classes.

Link to comment
Share on other sites

I really appreciate you sticking with me on this.

 

I will have a play around with it, even adding other objects like basing it on a person then maybe converting that to a database function class, like making a connection to a database for now then doing queries.

 

Just out of pure curiosity on the OOP with databases, I know this could be about personal taste, but would it be worth (or would I have to) doing something like this:

 

$mysql_db as new (class name);

 

I was just trying to write my own function but would I set mysql_connect() into a function as a variable and say if no database connection made connect?

 

Just wanted to check my logic theory in this respect.

 

Thanks again, looks quite exciting to be honest haha.

Link to comment
Share on other sites

For MySQL PHP already offers OOP extension called mysqli, so there's no need in creating your own (you can however extend it to add your own functionality).

 

Many people think OOP is about fancy syntax. It is not. OOP is about following simple (conceptually) rules, that force you to code in a specific way.

 

Theoretically you could create an entire application as a single class, but that could hardly be called OOP, evn though you used object oriented syntax.

Link to comment
Share on other sites

For MySQL PHP already offers OOP extension called mysqli, so there's no need in creating your own (you can however extend it to add your own functionality).

 

Many people think OOP is about fancy syntax. It is not. OOP is about following simple (conceptually) rules, that force you to code in a specific way.

 

Theoretically you could create an entire application as a single class, but that could hardly be called OOP, evn though you used object oriented syntax.

 

Ahh yes of course I mean I understood what OOP was all about, just didnt fully appreciate until I started learning how to write very simple code at how managable it is.

 

Its definately helping me understand some code I am expected to understand in my workplace, your replies have been invaluable to me really and I really thank you for that!

 

Going to keep cracking on with it finding out things about it and try to develop as many as I can in my own applications, just so I can get more experience in using it, but what you have said, I will keep coming back to.

 

Thanks ever so much for your advice,

Jez.

Link to comment
Share on other sites

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.