Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Classes:: Why declare as a new? [closed]

I'm very new to php classes and I was wonder why do I need to declare it to a variable and set it as NEW?

Here is an example :

class myFirstClass {
    function Version(){
        return 'Version 1';
    }
    function Info(){
        return 'This class is doing nothing';
    }
}

$hola = new myFirstClass;

echo $hola->Version();

Why this won't work WITHOUT declare it to a variable and set it to NEW ?

In other words... Without this line :

$hola = new myFirstClass;

I'm so used to functions so it looks weird to me...

like image 630
Steve von Johnson Avatar asked Dec 04 '25 13:12

Steve von Johnson


2 Answers

This is a basic principle of Object Oriented Programming (OOP). Let's use a library system for example. If you want to get the name of a book, you cannot just say "give me the name of the book", you have to know what book (by id, author, whatever).

In functions, you can write one that looks like this:

function get_book($id){ // code }

In OOP it doesn't really work that way. You have a class book that keeps a name. But that name is only for that given book.

class Book {
  var $name;
  public __construct($name) {
    $this->name = $name;
  }

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

In order to call the getName() function we need to have a book. This is what new does.

$book = new Book("my title");

Now if we use the getName() function on $book we'll get the title.

$book->getName(); // returns "my title"

Hope that helps.

like image 130
Friso van Dijk Avatar answered Dec 07 '25 04:12

Friso van Dijk


You are right! It is not necessary to use the new operator:

class myFirstClass {
    static function Version(){// static keyword
        return 'Version 1';
    }
    function Info(){
        return 'This class is doing nothing';
    }
}

echo myFirstClass::Version();// direct call
like image 40
Ruben Kazumov Avatar answered Dec 07 '25 02:12

Ruben Kazumov