Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Can you give me an example that consist the function __construct and how that code would be if we convert it into procedural php? Maybe this is a kind of dummy question for you, but for me who never learning php oop before really got confused when i met this new function.
For example, in this code, function _construct used to instantiate a new class.
Class Car{
private $brand;
private $type;
public function __construct($merk, $type){
$this->brand= $brand;
$this->type = $type;
}
public function getCar() {
return "<strong>Brand:</strong> " . $this->merk . "<br /> <strong>Type:</strong> " . $this->type;
}
}
But I'm found new example which only contain this code :
Class Game{
public function __construct()
{
echo "Blah";
}
}
Why on the last example, function __construct just contain the word echo "Blah" not contain this code too --> $this->whatever word ?
The __construct method is usually the method called in a class when an instance of that class is created (called an object). The method is called the constructor because it constructs the object, but that doesn't mean you must use the method to do so.
The point of the method is to set the variables of the object to their inital values, which may be a primitive type such as an integer, or perhaps an instance of another class. If the variables are to be something other than a default value, the __construct method can accept arguments to set the values of the variables.
You don't have to set the variables using the constructor method, nor is it the only thing you can do. You could, for example, print a success message or call another method, either in that class or elsewhere. So your two examples are both valid. The first is how you would expect the constructor to be used, but the second is still vaild. Like I said, __construct is the method that is called on creation of the object, which doesn't mean you have to use it for the intended purpose.
In PHP, it is not required to have a constructor method in a class, but in many other object orientated programming languages, such as Java, if a constructor is not present then it will produce an error at compile time. This is because PHP is what is know as a weakly typed language, which has many pros and cons which you can research further.
Because __construct is one of the magic methods specifically used in a PHP class, it cannot be converted into procedural code. To call the method with arguments, when you assign a class in your code you should give your arguments in the creation statement, like this;
$object = new MyClass($arg1,$arg2);
You cannot call the constructor from outside the class, other than when creating a new object. The only exception to this is a child class (ie, a class that extends another class) can call the constructor of its parent using parent::__construct();.
The constructor is meant for to instantiate a new Class (not neccessarly though) like the example below:
<?php
Class Car{
private $brand;
private $type;
public function __construct($brand, $type){
$this->brand= $brand;
$this->type = $type;
}
public function getCar() {
return "<strong>Brand:</strong> " . $this->merk . "<br /> <strong>Type:</strong> " . $this->type;
}
}
$car= new Car('Audi', 'A3');
echo $car->getCar();
/* Will return:
Brand: Audi
Type: A3
*/
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I learning a bit of OO PHP but the docs I came across showed a couple of methods of the following examples. I am confused as to why both work, and which should be used exclusively.
I know that #1 is not OOP but I was still curious about the second method of echo, and if it should be used or not.
Both of the echo's below print "Lansana", but one initializes $name before the echo whereas the other initializes it after (or during) the echo.
<?php
$name = "Lansana";
echo $name;
echo $name = "Lansana";
?>
Notice how there is a public property $name with no value in the first example, and no public property in the second, yet both still work the same.
class Pets
{
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$dog = new Pets("Buddy");
echo $dog->name;
class Pets
{
public function __construct($name) {
$this->name = $name;
}
}
$dog = new Pets("Buddy");
echo $dog->name;
What is the preferred method in #1 and #2, and why? I don't know why the docs showed the first class method because I don't see the need for a public property there, but then again what do I know.
Thought I should give a little more context to what I outlined in the comments above.
For the First example try not to mix assignment and output in the same statement. Although it is syntactically correct it doesn't immediately indicate the intent of the statement.
For the second example as I stated in the comments explicitly defining properties is always preferable. The advantages are:
Most IDE's will auto-complete defined properties for you minimizing the risk of mistyping a property.
It clearly indicates to someone reading the code what properties are available on the object.
It allows for you to set the visibility of the property so you can control more how your class is used which promotes encapsulation.
One of the most common bugs that you see with OO PHP is when you silently create a property for example something like:
class A {
public function setUserId($id){
$this->userId = $id;
}
public function getUserId(){
return $this->userid;
}
}
The intent is clear here but you have to be paying pretty close attention to the fact that the referenced properties are cased differently. If becomes much harder if you throw in another 50 lines of code and the two property references aren't on the screen at the same time.
On of the uses for PHP's magic __get and __set method are to help eliminate this problem earlier in development. Example:
class A {
public $foo;
public $bar;
public function __set($prop, $val){
throw new Exception ($prop." does not exist on this object");
}
public function __get($prop){
throw new Exception ($prop." does not exist on this object");
}
}
This makes it where if you attempt to access an undefined property the class will throw an exception letting you know exactly what happened and where.
I think #1 is just a shortcut. #2 is because of overloading, where class variables are created dynamically.
http://www.php.net/manual/en/language.oop5.overloading.php
As for preferred methods, with #1 'echo $name = 'Something'` more of a short cut than a different method. The end outcome is the same in either case.
With #2, dynamically created variables are not usually a good idea as it can generate some unexpected results but they do have their place. Check the link above for some example of code using overloading. The first method is favored.
1
echo $name = "Lansana";
PHP interprets it as
echo ($name = "Lansana");
echo sort of works like a function, because of that php interprets everything on the right side of the echo before sending it to standard out.
2
The first one is definitely the best way. Because PHP is a dynamic language (as opposed to a static language like C# or Java) it allows one to create and set variables without declaring them first. It is the best to always declare class variables--it makes the code easier to read and maintain.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
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...
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.
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
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
The Basics
http://php.net/manual/en/language.oop5.basic.php
Classes and Objects
http://php.net/manual/en/language.oop5.php
This line:
$hola = new myFirstClass;
Is saying: create a new object called $hola, then put a new instance of myFirstClass into $hola. Now $hola is literally a object containing a new instance of myFirstClass.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
$Clint_ip=$this->request->clintIp();
May I get a clear concept about this line?In here I know $clint_ip is a variable,but what is the next three?which one is an object?
which one is a method?
which one is a class?
I just need to understand this line.In several project I have seen this types of line.In this line which one called object?If you want You can give another example.In here $this is an object?or class?or method?
Yes $Clint_ip is an variable,
Like other object oriented based programming languages $this is the this of a class consisting it. (For more about this When to use self over $this?)
request looks like an object of another class
and clintIp() is the public method of the class of the request object
The code you provided appears to be from inside of a class.
A class is denoted like this:
class Example {
private $foo;
public $bar;
public function __construct() {
}
public function method() {
}
private function other() {
}
}
When you create an object of this class, you can use the format:
$example = new Example();
This calls the constructor __construct().
Once you have created ("instantiated") this object, you can use the -> to call the properties of the object.
So, I can say
$example->bar = "Foo";
which sets this property to a string.
Your Code
In your code, the property "request" is itself an object (an instance of a class).
$Clint_ip=$this->request->clintIp();
Here is an example of the code this could be using
class Example {
public $request;
public function __construct($request) {
$this->request = $request;
}
}
class Request {
public function clintIp() {
//return something
}
}
And then some context:
$request = new Request;
$example = new Example($request);
$clint_ip = $example->request->clintIp();
So here, $clint_ip is the variable. $example and $request are objects (instances of classes), and clintIp() is a method of the request object.
Now, about "$this". This indicates that it is within the object "Example":
Imagine the class Example now has a method
public function test() {
return $this->request->clintIp();
}
$this means that it is inside of an instance of an object. In static context, use "self::", as mentioned in one of the other answers.
You are inside object which has request property. Request property contains object with method clintIp() which return client ip.
This question already has answers here:
PHP: Static and non Static functions and Objects
(5 answers)
Closed 8 years ago.
I am still learning OOP PHP and I keep swapping and changing between the following way of calling methods within an object
$obj = new Model();
$obj->method($param);
against
Model::method($params);
I understand the difference when I within the method as I can use $this in the first example, and I have to use self:: in the second.
Which is the correct way and what are the reasons of using each way
The reason I ask is I cannot find a suitable search term to research. I am currently reading a book on OOP and it will probably tell at some point, but would be nice to know now.
Foo::bar() calls the static class method, while $foo->bar() calls the instance method on an object. These are two completely different things. You do not need an object instance to call Foo::bar(), and in fact you do not have access to instance data when doing so. Foo::bar() is essentially nothing else but a regular function call like bar(), except that the function is attached to a class.
Instance methods act on a specific object instance:
class User {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public static function hi() {
// no access to $this->name here, since static
// methods are not bound to specific instances
echo 'Hi';
}
}
$dave = new User('Dave');
$mary = new User('Mary');
echo $dave->getName(); // Dave
echo $mary->getName(); // Mary
User::hi(); // Hi
Unless you understand this, you know nothing about OOP.
First example is a non-static call to the method, second a static call.
The first is better if you want to access private variables of your Model, second is better if you use the method like a normal function.
In general you should declare methods of the first type as static (public static function method(){}).
First case is invocation of method on class instance, second case is call of static method.
See http://php.net/manual/en/language.oop5.static.php
There is no "proper" way because both call types serve different purposes.
The first call type is the standard way of handling objects: You initialize a concrete instance of a class. This instance can have its own internal values and each instance can use these values to create a different result when you call the method with the same parameter.
The second call type is called static and operates directly on the class, there is no instance (hence no $this). There are some use cases for it, see this answer for Java, it's the same for PHP.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm learning PHP so bear with me. Both of these classes set either a public or private variable, before it is used. Why is this?
class test {
public $name; // called here
public function __construct ($name) {
$this->name = $name;
}
}
$testing = new test('Hello');
echo $testing->name;
and:
class db_link {
private $link; // called here
public function __construct ($database_name) {
$link = mysql_connect ("localhost", "your_user_name", "your_password");
mysql_select_db ($database_name, $link);
$this -> link = $link;
}
function query ($sql_query) {
$result = mysql_query ($sql_query, $this -> link);
return $result;
}
function __destruct() {
mysql_close ($this -> link);
}
}
$db = new db_link ("MyDB")
$result = $db->query ("Select * from MyTable")
When you are declaring a class as in your example, you are setting up the skeleton for not only what it is, but what it CAN be. The declaration should really include anything and everything that will ever be inside the object - whether or not it will always be used.
In this case it's like saying the object can have hands and fingers, but not all the instances of the object will actually have them.
Although PHP allows some really interesting code (like creating a new property the first time that a value is assigned to it) even if it isn't part of the original object, it's generally considered bad form - and makes it almost impossible to track down errors in the code later.
I can't more strongly suggest only ever using properties that are declared and not just adding things on the fly.
This is to initialize the variable and explicitly set it to public or private so you don't have to hunt through the code for the information.
Variable initialization is a common programming practice in many languages.
They're declaring these variables to be members of the class. If you declare a variable inside of a function, it only exists within the functions 'namespace.' Once that function ends, the variable is deleted. Declaring external to functions allows the variables to inhabit the class' namespace, which means they are accessible to any functions that are methods of the class.
Quick Edit: this also means that the variables will be inherently tied to the class so instances of the class will contain those variables allow them to be accessible and modifiable through accessors and mutators. All in all, it's a very sound method both for reliability and accessibility.
You can declare your member variable anywhere, e.g. this will work:
class test {
public function __construct ($name) {
$this->name = $name;
}
public $name; // member variable $name
}
$testing = new test('Hello');
echo $testing->name;
However it is much more clear if you declare your member variables at the top of the class. Why? Because it is just trivial to be able to clearly see what variables a class is using...
I think I know what you're asking. This is related to Scope.
The variables that are passed to the constructor are available only until the constructor function completes. To register the variables as members of the object you need to assign them to a parameter of the class. Hence:
public $name; // called here
public function __construct ($name) {
$this->name = $name;
}
You can name the variable that is passed to the constructor anything you like (e.g. __construct($argument); $this->name = $argument;).
You're really just telling the constructor to expect a variable when the object is created. It is a common convention to name the variables passed to the constructor the same of the property name to help with readability, but there is no name conflict as the constructor variable does not share scope with the object parameters. the logic of doing this is that it is easier to understand where the variables passed to the constructor are going to be assigned.
so __construct($name) and public $name; ($this->name) are two completely separate pieces of memory .
I hope this helps. I remember what it was like trying to get my head around things like this.