Can't instantiate a class inside another PHP - php

How can I instatiate athe class OM inside the MySQL_DataMapper?
Here is the MySQL_DataMapper.php:
<?php
namespace asc {
include('../../models/OM.php');
class MySQL_DataMapper
{
[omitted code for simplicity]
public function fetchAllOMs()
{
$query = "REALLY LONG QUERY";
$result = $this->pdo->query($query);
$OMs = array();
while ($row = $result->fetch()){
$OM = new OM($row['id_organizacao_militar'], $row['nome'], $row['sigla'], $row['forca_armada']);
array_push($OMs, );
}
var_dump($OMs);
}
}
}
Here is the error I get:
Warning: include(../../models/OM.php): failed to open stream: No such file or directory in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php on line 10
Warning: include(): Failed opening '../../models/OM.php' for inclusion (include_path='.:/usr/share/php') in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php on line 10
Fatal error: Uncaught Error: Class 'asc\OM' not found in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php:37 Stack trace: #0 /home/alekrabbe/PhpstormProjects/stm_asc/views/cadastro-militar.php(13): asc\MySQL_DataMapper->fetchAllOMs() #1 {main} thrown in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php on line 37
I don't understand why it fails as I did just that on another php file and it worked there. Thank you.
EDIT 1
Forgot to mention but the class OM.php is also in the asc namespace.
Here it is:
<?php
namespace asc{
class OM
{
private $id;
private $nome;
private $sigla;
private $forca_armada;
public function __construct($id, $nome, $sigla, $forca_armada)
{
$this->id = $id;
$this->nome = $nome;
$this->sigla = $sigla;
$this->forca_armada = $forca_armada;
}
[Gets and Sets]
}
}

You're inside a namespace:
namespace asc {
So references to OM become asc\OM. Fix this by anchoring to the root namespace:
$OM = new \OM(...);

Try include __DIR__ . "/../../models/OM.php"; and make sure the path is correct
EDIT: the better way is to use an autoloader as #Alex Howansky mentioned in a comment on his answer, but in a pinch just make sure the path is correct and use DIR.

Related

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct() on PDO class

I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:
[16-Sep-2022 11:05:02 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
Stack trace:
#0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
#1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
#2 {main}
thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11
I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:
error_reporting(E_ALL ^ E_NOTICE);
define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
define('I', 'interfaces/');
// Management
require_once C . 'config.php';
// Interfaces
require_once A . I . 'interface.engine.php';
require_once A . I . 'interface.core.php';
require_once A . I . 'interface.template.php';
// Classes
require_once A . 'class.engine.php';
require_once A . 'class.core.php';
require_once A . 'class.template.php';
// OBJ
$engine = new Kit\engine();
$core = new Kit\core();
$template = new Kit\template();
// Start
session_start();
$template->Initiate();
This references the class.engine.php first which is where I have created the database connection class, as shown below:
namespace Kit;
use PDO;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class engine
{
public $pdo;
public function __construct()
{
global $_CONFIG;
$dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
} catch (\PDOException $e) {
print "<b>An error has occurred whilst connecting to the database:</b><br />" . $e->getMessage() . "";
die();
}
}
}
$connection = new engine();
I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:
namespace Kit;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class core implements iCore
{
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function website_settings()
{
$qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
$qry->execute([]);
if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
}
}
Sorry if this is a simple fix but I really can't see where I'm going wrong.
Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed
Just guessing, but i think
$core = new Kit\core($engine->pdo);
will fix your issue.

PHP- PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function SignupContr::signupUser()

I am new to OOP php and took some lessons and now Im trying to practice, I used login with discord method and If user Is logged in the system sould add the discord id to database if user is not already in database but Im facing quite the issue and I have no luck so far to fix It myself, I even asked few of my buddies If they can see the issue but they did not also know the real issue.
My error:
[22-Jul-2022 06:56:00 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function
SignupContr::signupUser(), 0 passed in C:\wamp64\www\OOP-Test\inc\signup.inc.php on line 13
and exactly 1 expected in C:\wamp64\www\OOP-Test\classes\signup-contr.class.php:10
Stack trace:
#0 C:\wamp64\www\OOP-Test\inc\signup.inc.php(13): SignupContr->signupUser()
#1 C:\wamp64\www\OOP-Test\dashboard\index.php(12): include('C:\\wamp64\\www\\O...')
#2 {main}
thrown in C:\wamp64\www\OOP-Test\classes\signup-contr.class.php on line 10
My code looks like this right now:
signup.inc.php
{
$discord = $_GET['user'];
include "../classes/dbh.class.php";
include "../classes/signup.class.php";
include "../classes/signup-contr.class.php";
$signup = new SignupContr($discord);
$signup->signupUser();
//header('location: ../dashboard/index.php');
}
signup.class.php
class Signup extends Dbh {
protected function setUser($discord){
$stmt = $this->connect()->prepare("INSERT INTO `users` ('discord') VALUES (?);");
if(!$stmt->execute(array($discord))) {
// $stmt = null;
// header("location: ../dashboard/index.php?useraddfailed");
// exit();
}
$stmt->debugDumpParams();
$stmt = null;
}
}
signup-contr.class.php
class SignupContr extends Signup{
private $discord;
public function _construct($discord){
$this->discord = $discord;
}
public function signupUser(){
$this->setUser($this->discord);
var_dump($this->discord);
}
}
I have not done the check part If user Is allready In the database
I Finally found the issue. I was missing one underscore in construct.
signup.contr.class.php should be like this:
class SignupContr extends Signup{
private $discord;
public function __construct($discord){
$this->discord = $discord;
}
public function signupUser(){
$this->setUser($this->discord);
var_dump($this->discord);
}
}
Of course it was the simplest issue there Is but I really tought there suppost to be only one underscore. You always should check the simple things first, I did not because usally you don't use construct In procedural php

Class not found although it's in an included file

In my main page (index.php) I've included "class_lib.php" which contains the class definitions.
When calling the class from index.php - I'm getting the followin
Fatal error: Uncaught Error: Class 'person' not found in /home/latingate/public_html/test/ObejectOriented/index.php:5 Stack trace: #0 {main} thrown in /home/latingate/public_html/test/ObejectOriented/index.php on line 5
What am I doing wrong?
index.php
<?php include("class_lib.php"); ?>
<?php
$stefan = new person();
$jimmy = new person;
$stefan->set_name("Stefan Mischook");
$jimmy->set_name("Nick Waddles");
echo "Stefan's full name: " . $stefan->get_name();
echo "Nick's full name: " . $jimmy->get_name();
?>
class_lib.php
<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
}
?>
you can see it online here:
view online
Your code is correct and works for me.
I think Problems in file Path. So, first check your class_lib.php file is not in same directory then assign correct path.

error in getting the fetching path

I actually trying to check my connection in connection file tester to check if it is connected to the database but the problem is I got this error
Warning: include(obj\database_connection\SqlHandler.php): failed to open stream: No such file or directory in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16
Warning: include(): Failed opening 'obj\database_connection\SqlHandler.php' for inclusion (include_path='/home/devhostt/public_html/bcc/gradingsystemmodule:.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16
Fatal error: Class 'obj\database_connection\SqlHandler' not found in /home/devhostt/public_html/bcc/gradingsystemmodule/function/checkconnection.php on line 8
and here is my code to set & get the path (root.php)
<?php
error_reporting( E_ALL );
define("setRealpath", realpath("../"));
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE: ";
try
{
$getPath = array(setRealpath, get_include_path());
if(!set_include_path(implode($getPath, PATH_SEPARATOR)))
{
define("setRealpath", realpath("./"));
$getPath = array(setRealpath, get_include_path());
set_include_path(implode($getPath, PATH_SEPARATOR));
}
function GetClassFile($class)
{
$file = str_replace('/', '\\', $class).".php";
include $file;
}
spl_autoload_register('GetClassFile');
}
catch(Exception $x)
{
die(ERROR_EXCEPTION_MESSAGE.$x->getMessage());
}
?>
here is the file where my connection (SqlHandler.php).
<?php
namespace obj\connection_database;
use \PDO;
class SqlHandler extends Connection
{
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE:";
protected $db = null;
public function __construct()
{
$this->db = $this->getConnection();
}
public function checkConnection()
{
if($this->db)
{
return "CONNECTED";
}
return "NO CONNECTION";
}
}
?>
and lastly here in this file where i'm trying to check the connection(checkconnection.php)
<?php
error_reporting(E_ALL);
include "./root/root.php";
use \obj\database_connection\SqlHandler;
$checkConnection = new SqlHandler;
echo $checkConnection->checkConnection();
?>
now i found my mistake, the only mistake is that i'm using the old version of php, instead of using php 7.1 version , i'm using php 5. so i change it and it works.

How to have more than one include on the same page in PHP

The title says it all, I've been trying to get this to work but it isn't working for me. It is just displaying the first include.
<?php include 'config.php'; include 'https://theurl/that_the_header_is_on/header.php'; include '$header_url'; ?>
EDIT: The error is here:
[11-Dec-2016 03:26:13 Europe/Moscow] PHP Warning: include(): http://
wrapper is disabled in the server configuration by allow_url_include=0
in /home/myurlf/public_html/SimplePages/index.php on line 4
[11-Dec-2016 03:26:13 Europe/Moscow] PHP Warning:
include(myurl.fluctis.com/SimplePages/Default/1.0/header.php‌​):
failed to open stream: no suitable wrapper could be found in
/home/myurlf/public_html/SimplePages/index.php on line 4 [11-Dec-2016
03:26:13 Europe/Moscow] PHP Warning: include(): Failed opening
This should make code run. But...
<?php
include('config.php');
include('https://theurl/that_the_header_is_on/header.php');
include($header_url);
?>
Are you trying to do this? .. your post is a little confusing
<?php
include('config.php');
$header_url = 'Includes/header.php';
include($header_url);
?>
Try this. This is what I currently using.
/**
* Load all the class under RTlib\RTphp
*
* #return boolean False if error
*/
function RTphpLoad() {
$lib = array();
$lib[] = '/src/RTmysqli.php';
$lib[] = '/src/RTpassword.php';
$lib[] = '/src/RTslugify.php';
$lib[] = '/src/RTutil.php';
try {
foreach ($lib as $class) {
require_once dirname(__FILE__) . $class;
}
return true;
}
catch (Exception $ex) {
trigger_error('RTphpLoad() Fail to load. ' . $ex->getMessage());
return false;
}
}
In another php file
require_once FILEROOT . 'RTlib/RTphp/load.php';
RTphpLoad();

Categories