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.
Related
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
I'm new in PHP OOP and curious about method. How to make method inside method (I dont know what its name)?
For example, I can access like this
<?php
$myClass = new CarClass;
$myClass->createNew->bodySection->setColor("red");
Just like Codeigniter for calling a Models or Library using this.
<?php
$this->myLibrary->getData()
It's different from method chaining where between method call there is no parameter, its like javascript.
Can I achieve that? Or any alternative?
Thank you
Given the code,
$myClass = new myCar;
$myClass->createNew->bodySection->setColor("red");
we can make the following statements:
myCar has a property named “createNew”.
createNew holds some unknown object
The unknown object has a property called bodySection
The property named bodySection contains an unknown object that has a method named setColor()
Clear as mud?
There are several ways this could be illustrated; here’s one:
class myCar {
public createNew;
public function __construct() {
$this->createNew = new Foo;
}
}
class Foo {
public bodySection;
public function __construct() {
$this->bodySection = new Bar;
}
}
class Bar {
public function setColor($color) {
echo "Color is $color";
}
}
$myClass = new MyClass;
$myClass->createNow->bodySection->setColor('red');
// output: Color is red
The first problem here is that “createNow” doesn’t make sense as a property; it’s an action, not something that a myCar would own or do.
Likewise, a bodySection would probably have a color as a property, to be set with its own setter method, not some external object.
Bottom line, making long chains of pointers is not something to seek after; rather, they’re probably better kept as short as possible. Otherwise your object probably knows too much about to many things.
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 4 years ago.
Improve this question
I found that calling the static method via object can be very convenient in some use case.
I'm wondering if this is is considered as a bad practice?
or if this feature will be removed in the future version of PHP?
class Foo
{
public static function bar ()
{
echo 'hi';
}
}
class SubFoo extends Foo
{
public static function bar ()
{
echo 'hi subfoo';
}
}
// The normal way to call a static method.
Foo::bar(); // => "hi"
// Call the static method via instance.
$foo = new Foo;
$foo::bar(); // => "hi"
// Here is the use case I found calling static method via instance is convenient.
function callbar(Foo $foo)
{
// The type-hinting `Foo` can be any subclass of `Foo`
// so I have to figure out the class name of `$foo` by calling `get_class`.
$className = get_class($foo);
$className::bar();
// Instead of the above, I can just do `$foo::bar();`
}
callbar(new SubFoo); // => "hi subfoo"
As a general rule, using static methods is bad practice because:
In fact, static methods or static variables are global variables
static code makes can cause many troubles in testing
static code makes high cohesion between parts of code
static code makes hidden dependencies between parts of code
But, there are cases when using static code is justified. For example:
Methods refer to a class and don't refer to objects
Helpers or Util classes which don't have their states
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
*/
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to make the switch to OOP. I found a pdf on the internet written by killerphp that seems useful. Followed his examples up 'till now because I got an error. The output is this:
Warning: Missing argument 1 for person::__construct(), called in
C:\xampp\htdocs\oop\index.php on line 15 and defined in
C:\xampp\htdocs\oop\class_lib.php on line 8
and
Notice: Undefined variable: persons_name in
C:\xampp\htdocs\oop\class_lib.php on line 10
Stefan's full name: Stefan Mischook
Nick's full name: Nick Waddles
This is index.php (the page that I run):
<?php
require_once('class_lib.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OOP in PHP</title>
</head>
<body>
<?php
// Create object without constructor by calling a method
$stefan = new person();
$stefan->set_name("Stefan Mischook");
echo "Stefan's full name: " . $stefan->get_name();
echo "<br>";
// Create object with constructor
$jimmy = new person("Nick Waddles");
echo "Nick's full name: " . $jimmy->get_name();
?>
</body>
</html>
And here is the class:
<?php
// A variable inside a class is called a "property"
// Functions inside a class are called "methods"
class person
{
var $name;
function __construct($persons_name)
{
$this->name = $persons_name;
}
function set_name($new_name)
{
$this->name = $new_name;
}
function get_name()
{
return $this->name;
}
}
// $this can be considered a special OO PHP keyword
// A class is NOT an object. The object gets created when you create an instance of the class.
// To create an object out of a class you need to use the "new" keyword.
// When accesign methods and properties of a class you use the -> operator.
// A constructor is a built-in method that allows you to give your properties values when you create an object
?>
Nevermind the comments, I use them for learning. Thank you very much and please let me know if I need to edit my question before downrating. Cheers!
The problem is here:
// Create object without constructor by calling a method
$stefan = new person(); // <-----
$stefan->set_name("Stefan Mischook");
You're not passing a required parameter to the constructor.
function __construct($persons_name)
{
$this->name = $persons_name;
}
This (constructor) requires a $persons_name argument to construct a new instance of the person class.
Also (related), your comment // Create object without constructor by calling a method is not at all what the code is doing. You are calling the constructor, and that is the problem. Perhaps this was partially copied from some example, and you missed something?
Your example would work without error if you replace your following line:
function __construct($persons_name)
for this one:
function __construct($persons_name='')
so specifying a default empty string for the constructor of the object.
Try this:
$stefan = new person("something");
$stefan->set_name("Stefan Mischook");
And it's better to use CamelCase for the class names.
If you want to be able to call a method without (some) of it's parameters then you need to define their default values.
public function __construct($persons_name = NULL) {
/* do something with $persons_name */
}
Otherwise the function will expect the parameter to be required and would yield a Notice letting you know about the incorrect function call.
You have specified a __construct method/function. When creating a new object of that class it's going to be called. Now it just happens to be so that you've said it requires one argument, and you didn't give it one when you made an object of the class. Here's how it should have been:
$stefan = new person('Stefan Mischook');
No need to use the set_name method/function later on then, unless you want to change it.
You could also have done this to your __construct method/function:
function __construct($persons_name='')
What this does is to auto assign $person_name to be an empty string unless you give it an argument, in which case the argument you give will replace the empty string.