PHP OOP - Missing argument 1 [closed] - php

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.

Related

Multiple Method Access Inside Class PHP [closed]

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.

Issues with dependency injection in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I looked at the problems here on SO, and tried to fix the code accordingly, but I'm having a hard time understanding why this is not working.
I have a class in its namespace, and I'd like to use the methods from another class from another namespace in it. So I tried:
<?php
namespace Main_Namespace\My_Namespace;
use Other_Namespace\Cool_Class;
class Main_Class {
protected $cool_class;
public function __construct( Cool_Class $cool_class ) {
$this->cool_class = $cool_class;
}
public test_method() {
$some_boolean = $this->cool_class->some_method_that_returns_bool();
}
}
And I instantiate it elsewhere with new MainClass().
This fails, and tells me
PHP Fatal error: Uncaught TypeError: Argument 1 passed to Main_Namespace\My_Namespace\Main_Class::__construct() must be an instance of Other_Namespace\Cool_Class, none given, called in...
I even tried with
use Other_Namespace\Cool_Class;
$cool_class_instance = new Cool_Class();
new Main_Class( $cool_class_instance );
Not working as well (I think I get class not found error).
Now, if I don't instantiate in the constructor, but inside a method like
<?php
namespace Main_Namespace\My_Namespace;
use Other_Namespace\Cool_Class;
class Main_Class {
public test_method() {
$cool_class = new Cool_Class();
$some_boolean = $cool_class->some_method_that_returns_bool();
}
}
This will work.
What am I missing here? What am I doing wrong?
For the first example:
$myObject = new MainClass();
The error you get is expected. You cannot call an empty constructor for a class that has a constructor with a typed parameter.
For the second example (calling a constructor with an initialized object as a parameter, which fails):
Edit: added details missing in the original quesion.
Please specify exact error message that you received - class load error
Please specify PHP version - 7.1
Please provide the custom autoloader - link in comment.
I suggest to debug the autoloader by dumping the values it is processing.
Example 3 is ok.

A few PHP questions (echo / OO PHP) [closed]

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.

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

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.

What is the function __construct in PHP used for? [closed]

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
*/

Categories