Who could illustrate PHP?

Hello,

What I mean, who could illustrate the difference between Function and Class ?
Where we should use each of them ? for example, could we use only functions to build a simple dynamic website ?

Regards,
BB

The difference… Well, they are very different, a better question will be what similarity they share. They both exist for code reuse, since you dont want to write duplicate code. The major difference is that functions do not contain any data of its own, it only accepts data from client code and uses it. Classes on the other hand, is usually combination of data and behaviors, its more advanced and complicated than functions. Classes may accept arguments/parameters from client code too, but usually they also are containers of their own data, such data is hidden from public and well encapsulated.

In general, functions are used for procedural programming, if you have a small personal home page it will suffice. Classes are on the other hand, for writing professional object oriented code, it is the standard for enterprise large scale application. But using functions or classes doesnt necessarily mean you are writing procedural PHP or OO PHP, theres more complexity to it. You will understand what I mean a bit later.

It is totally possible to build a simple dynamic website with only functions(or if its simple enough, you dont even need functions, just a few lines of unorganized code will do), as PHP allows you to write your code in procedural way. But if you expect to develop your site continuously over years, and that it will grow into larger application, its necessary to use classes and build an architecture of object oriented software.

1 Like

In the simpliest case you can think of Class as a collection of functions.
That means classes allow you to group functions which work with the same context.

For example, if you’re writing blog platform, you have functions that handle posts.
They can look like this:

//procedural way
$post = post_get($id);    
post_update($post, $newText);
post_change_author($post, $newAuthorId);
post_save($post);

or like this:

//OOP way
$post = new Post($id);
$post->update($newText);
$post->setAuthor($newAuthorId);
$post->save();

or even this:

//OOP with chaining
Post::get($id)->update($newText)->setAuthor($newAuthorId)->save();

Other aspect here is that OOP (classes) allows you to make better logic separation.
For example, lets say that you have two post types in your blog system.
And each of them should be saved in different storage.
How could you deal with it using functions?

function post_save($post, $type){
    if ($type == REGULAR_POST){
        //save to database
    }
    if ($type == PHOTO_POST){
        //save to file
    }
}

Not so complicated when there is only two post types.
But how about dozen of them? You’ll get one big mess of IFs in your function.

While using OOP you could define different classes in separate files:

class RegularPost {
    public function save(){
        //save to database
    }
}

class PhotoPost extends RegularPost {
    public function save(){
        //save to file
    }
}

And keep that logic clear, no matter how many post types do you have.

Sorry for the long post, hope it’ll help :smiley:

3 Likes

Hello,

Thank you both for your help, I really appreciate your way to explain the idea. I write the following simple code, just to understand the relation, but nothing working :smile: in the same time I’m happy, I’m testing /

<?php
class names{
public $a; 
public $b;
public $c;
public $d;
function __construct($a,$b,$c,$d){
   $this->a = $a;
   $this->b = $b;
   $this->c = $c;
   $this->d = $d;
return array(a,b,c,d)
}
}
    
list($apple,$born,$content,$document) = new names(" Apple "," Born "," Content "," Document ");
echo $apple;
?>

I was thinking to write a class, add variables, and if everything ok, add foreach and use shuffle or array_rand() to display the names each time in different way. like the following

Apple  Born  Content  Document 
Born  Content  Document Apple  
Content  Apple  Document Born  

It was just something to learn and to enjoy coding.

You have an error here:

 return array(a,b,c,d)

What is a,b,c,d?
Hint: They don’t prepended with $ so they aren’t valid variables

Well your class doesnt look good, as your constructor should not return any values. I think in most programming languages, it will throw an exception or error at you, but maybe PHP allows this? Anyway, its not a good practice, you should design your class like this:

class Names{
private $a; 
private $b;
private $c;
private $d;
public function __construct($a,$b,$c,$d){
   $this->a = $a;
   $this->b = $b;
   $this->c = $c;
   $this->d = $d;
}

public function toArray(){
    return array($this->a, $this->b, $this->c, $this->d);
}

You will call new Names(" Apple “,” Born “,” Content “,” Document ")->toArray() to get the array representation of your object then.

2 Likes

I was really testing to see what I will get.

Thank you

I’m sure you are right, but permit explain what you did just to be sure that I understood your script well.

Ok here you declare variables, I don’t know why you make them PRIVATE, and keep functions PUBLIC.

here you inject the 4 variables by the contruct inside the body of the class.

here you associate the 4 variables to an array in the body of the class.

I’m gonna make a test and back to here, I hope I will get success. By the way, as I’m using an array here, I think I will be able to use foreach ? I will give it also a try

Thank you

Well these object member variables(called properties) should be private by default(or protected if you are sure your class will and should be extended). For object member functions(called methods), they can be either public or private, depending on whether you want the methods to be a part of your API. This is what we call encapsulation, you should not be able to access your properties from outside of your class/object, and you only expose public methods when you are sure you should.

1 Like

When we talk about object properties (class variables) it is a good practice to keep them private and provide getter and setter methods (functions) instead. This can help you to validate or pre-proccess values that other code assigns to your variables later.

Let’s say, for example, there are such lines in many places of your application:

$names->a = "Apple";

And one day you’ve decided to change logic of your class. Say, now you want all properties to be lowercase. That means you need to find all of those assignments around your code and change “Apple” to “apple”.

To avoid such situations setters were invented. You add a function in your class:

public function setA($newA){ $this->a = $newA; }

and declare $this->a as private. In other code you assign values through your setter:

$names->setA('Apple');

and when you want to accept only lowercase values you can simply modify your setter:

public function setA($newA){ $this->a = strtolower($newA); }

That’s it. Other code can still provide capitalized values and at the same time you’re sure that you receive only lowercased.

1 Like

Thank you both really again and again for your help. I will read again and again this evening your comments, as I’m understand better now the things ( I hope ).

A very quick question, before get back to you both, why when put the following code at the end of the code provided by Hall_of_Famer /

$hello = new Names(" Apple "," Born "," Content "," Document ");

echo $hello->toArray(2);

I get just the word (Array) in the browser. Normaly the work (Content) that should appear, No ?

Well of course you got the word array to browser, since in PHP array cannot be converted to string automatically. To fix this, just change the last line to:

echo print_r($hello->toArray(), TRUE);

Thanks to your help, the script works very good now ( in fact, without you, I have not had the opportunity to get it work)

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
class Names{
	private $a; 
	private $b;
	private $c;
	private $d;
	public function __construct($a,$b,$c,$d){
	   $this->a = $a;
	   $this->b = $b;
	   $this->c = $c;
	   $this->d = $d;
	}
	public function toArray(){
		return array($this->a, $this->b, $this->c, $this->d);
	}
}

$hello = new Names(" Apple "," Born "," Content "," Document ");

foreach ($hello->toArray() as $result){
	echo $result ;
  }

?>

I’m trying now to display the 4 words randomly, but to be honest, it is not a simple issue, I will back to you soon.

Many thanks again…

Codeacademy has a fairly good interactive tutorial to get your feet wet with PHP OOP.

There is also a good bit of material to take in here too.

Scott

1 Like

Thank you for your advice

About Codeacademy, I like it and test it also, but it is still “light” as content, teaching just the basic. In fact, I learn now the tutorial of Kevin Skoglund on Lynda.com ( PHP with MySQL Essential Training ). He is really explaining slowly each thing in PHP during the 131 videos of his course. So I got an general idea about PHP and its variable, functions, arrays, and still learning. But you know, I like to make some small codes to understand the things more, and I come to here to share my experience.

I’m really have the chance to get the help of SitePoint’ members here, like Hall_of_Famer, megazoid, and other…their way to support learners like me is really very helpful.

Great you are learning, but I just quickly took in the course titles and it doesn’t look like Kevin is teaching OOP practices. In fact, in this preview video, Kevin is saying take his subject CRUD scripts and do a copy and paste of the code for the page CRUD scripts. That is exactly what you should be avoiding, when working with OOP. “Copy and Paste coding”. This form of coding is no longer the standard anymore (was it ever?). So, although you may learn a few things about PHP in those videos, you are not learning how to do OOP.

So, although the Codeacademy exercises are basic, that is where you really need to start. Or with any other tutorial that teaches the core concepts of OOP. Once you get the basics down, then try your hand at coding something in OOP.

Scott

Exactly, and all what you talk about it is true. He is just talking about PHP, but I will learn other courses about OOP, as I like Laravel and choose it as framwork to built with my first future app with OOP.

You mean that Codeacademy will teach me also OOP during its lessons ?

Thank again for your interest.

It is OK, I found the answer on Codeacademy.
I’m on this website from 2 hours and half, and now reading about
“What’s Object-Oriented Programming?”

So I understand now s_molinari why you advice me to go to this website. Thanks !

Hello all,

Back to what you ( Hall of Famer) said before about properties /

I was learning yesterday on codeacademy following the advice of e_molinari /

They made in their example to present OOP, the following coed /

<!DOCTYPE html>
<html>
    <head>
      <title> Introduction to Object-Oriented Programming </title>
      <link type='text/css' rel='stylesheet' href='style.css'/>
    </head>
    <body>
      <p>
      <?php
        // The code below creates the class
        class Person {
            // Creating some properties (variables tied to an object)
            public $isAlive = true;
            public $firstname;
            public $lastname;
            public $age;
            
            // Assigning the values
            public function __construct($firstname, $lastname, $age) {
              $this->firstname = $firstname;
              $this->lastname = $lastname;
              $this->age = $age;
            }
            
            // Creating a method (function tied to an object)
            public function greet() {
              return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
            }
          }
          
        // Creating a new person called "boring 12345", who is 12345 years old ;-)
        $me = new Person('boring', '12345', 12345);
        
        // Printing out, what the greet method returns
        echo $me->greet(); 
        ?>
        </p>
    </body>
</html> 

As you can see, they were made the properties of Person class as Public, are you are with that ? It is very important for me to know why you choose Private and they choose Public ?

Thanks !

I looked up the code in academy, it is like your very first OOP example. The reason why I use private is that, it is better encapsulation. But encapsulation is an intermediate-level concept, and not every beginner understands it. If you read Matt Zandstra’s book PHP Objects, Patterns and Practices, he also illustrated the very basics of PHP with public properties. But even since access modifiers and encapsulation were introduced, he would use private or protected properties from then on.

Since you are an absolute beginner, you may not worry about access modifiers and encapsulation, just do what code academy is telling you. But once you get to the next stage, you should always keep your properties private. OOP is more than just using object oriented syntax, keep this in mind.

3 Likes

As @Hall_of_Famer mentioned, since you are beginning, don’t worry too much yet about why it might be better to have private properties above public ones. All you need to understand is what the difference is between public, protected and private properties and methods and the differences there are between them in relation to object and application scope. This is called “visibility”. Once you get that down, along with the other basics of OOP, then you can move on to the next level of concepts, like polymorphism, inheritance, encapsulation, SOLID, etc. Once you get that down, then you can move to design patterns. I can also recommend the book Hall_of_Famer mentioned from Matt Zandstra, once you get to that level, although, it also helps with the intermediate level too. Just get it. It will be good reading for you. :smile:

2 Likes