Issues with dependency injection in php [closed] - php

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.

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.

php class not saving variable [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 5 years ago.
Improve this question
I have a simple API class that talks with its web-based counterpart.
All works fine, just one variable denies to be saved.
I have a variable called $scope, initialised at the top of the class:
class Api {
private $scope;
public function set_scope( $s ) {
$this->scope = serialize($s);
return true;
}
private function get_scope() {
return unserialize($this->scope);
}
}
Next I'm getting the scope via API from the web script as JSON, I json_decode it as an array (second parameter as true) and in that form, I pass it through set_scope() function.
I am 10000000% sure API returns JSON, when var_dump'ed it returns me a proper array data.
For some reason though, that data is not saved into the $scope variable.
Any ideas?
Edit #1:
I call function get_scope within the class, in another function. I was trying to set that variable directly, so just using $this->scope=$scope, without success though. I use the same structured functions to save/get other variables, and all of them are working, except this one.
Other function looks like that:
public function get_modules() {
$av_modules = $this->available_modules;
$scope = $this->get_scope();
var_dump($scope);
foreach($scope as $mod) {
$av_modules[$mod] = true;
}
return $av_modules;
}
The get_scope method is private (thus cannot be called from outside itself).
Make the get_scope method public and the value will be returned.
Your get_scope() function is declare as private. To use it outside class, you should change it to public.

PHP object scope Call to a member function on null [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 5 years ago.
Improve this question
i have a class called Users.php .Inside of this class i create a local variable like this:
class Users
{
public $dbHelper;
}
inside of the Users class is a function called init inside of this function i set the $dbHelper variable to be a object of the DatabaseHelper.php class i wrote:
public function init()
{
$this->dbHelper = new DatabaseHelper();
}
now i try to call a method inside of the DatabaseHelper class like this:
public function login()
{
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
But currently its giving me this error:
Call to a member function executeSQLCommandWR() on null.
Why is the dbHelper variable null? In other oop programming langauages this works why not in this case?
Thanks for any help
Edit:
Im sorry i couldnt post all the code for this question because i was kind of in a rush when i created this question.
I call the init method as soon as my page gets loaded. It really seems like a scope problem i will try some of the answers and try to solve this problem. Thanks for everyone trying to help
I think you do not called the init, but init is not a good practice if you call it right after the instantiate. You can put it into the constructor, but that wont be a clean code too.
Instead of this use:
public function login() {
if (empty($this->dbHelper)) {
$this->dbHelper = new DatabaseHelper();
}
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
or
public function login() {
$this->init();
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
public function init() {
if (empty($this->dbHelper)) {
$this->dbHelper = new DatabaseHelper();
}
}
Second is better because of single responsible principle IMHO.
Notice that you have not initialized the member variable $dbHelper,
you haven't provided it with any value, therefore, it's null.
public function login()
{
$this->init();
$this->dbHelper->executeSQLCommandWR(// HERE COMES THE QUERY STRING //);
}
It seems to be a variable scope problem call the function init in the login function to define the variable

Call function inside class [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 8 years ago.
Improve this question
I'm trying to create a simple class in PHP, but i've got some trouble with a method call.
<?php
include('MySQL.php');
class User {
var $sql;
function _construct(){
// SQL connection
$this->sql = new MySQL(<<hidden>>, <<hidden>>, <<hidden>>);
}
public function login($username, $password){
// TODO
}
}
?>
At the //TODO section, i want to do a call like $this->sql->select('users'), but it won't let me do it. It gives an error and says that sql is a non-object.
Your "_construct" is missing a _ (you must have two), to it won't get called. Change it to :
public function __construct(){
It should work. Also remember to make it public.
If it's not called, you $sql variable isn't initialized and is actually a non-object for PHP.
Also, you may precise the visibility of your variable when declaring it, rather than using the deprecated var keyword :
private $sql;

PHP OOP - Missing argument 1 [closed]

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.

Categories