Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vs PHP - Object oriented questions:

Tags:

oop

php

I've been working in PHP lately and while I find the language pretty simple coming from C++/C#/python, etc, I have been running into some strange differences (maybe) when it comes to its OO representations. If anyone could answer a few short questions I would be very appreciative :)

  1. Can a constructor return a result value in PHP?

  2. When a member function within a class calls another member function within a class, do I have to use the self:: scoping or is that just a hint?

  3. Why is there self:: and $this-> and what's the difference?

  4. Is there any need to delete an object created with new, or will going out of scope remove it? I'm not sure if its truly dynamic, or if there's garbage collection like in C#.

I know the questions are a little simple, and I keep seeing code that uses all these things - but I haven't seen anything concrete enough and I don't have a good php book at home :) So thank you in advance for answers!

like image 676
John Humphreys Avatar asked Dec 17 '22 08:12

John Humphreys


1 Answers

1. Can a constructor return a result value in PHP?

No. (This was possible, but the issue has been fixed - in case you see code that suggests something else.)

2. When a member function within a class calls another member function within a class, do I have to use the self:: scoping or is that just a hint?

This normally technically works, please don't do so. Inside object instances use $this to access own properties and methods.

3. Why is there self:: and $this-> and what's the difference?

It's not the full answer, but for the intro: self:: is for static function calls and member access. See PHP: self vs. $this.

4. Is there any need to delete an object created with new, or will going out of scope remove it? I'm not sure if its truly dynamic, or if there's garbage collection like in C#.

You don't need to delete objects, there is a garbage collector. When objects leave scope they are deleted (the zval's container reference count is one). Keep in mind that everything is deleted at the end of the request in PHP. Your application normally only runs for a fraction of a second, then the process's memory is cleared anyway as the script (and PHP) terminated.

like image 188
hakre Avatar answered Dec 30 '22 03:12

hakre