I'm very new to PHP. I understand the concepts of OOP, but syntactically, I don't know how to extend a parent class from another file. Here is my code:
parent.php
<?php
namespace Animals;
class Animal{
protected $name;
protected $sound;
public static $number_of_animals = 0;
protected $id;
public $favorite_food;
function getName(){
return $this->name;
}
function __construct(){
$this->id = rand(100, 1000000);
Animal::$number_of_animals ++;
}
public function __destruct(){
}
function __get($name){
return $this->$name;
}
function __set($name, $value){
switch($name){
case 'name' :
$this->$name = $value;
break;
case 'sound' :
$this->$name = $value;
break;
case 'id' :
$this->$name = $value;
break;
default :
echo $name . " not found";
}
}
function run(){
echo $this->name . ' runs <br />';
}
}
?>
extended-classes.php
<?php
namespace mammals;
include 'parent.php';
use Animals\Animal as Animal;
class Cheetah extends Animal{
function __construct(){
parent:: __construct();
}
}
?>
main.php
<?php
include 'extended-classes.php';
include 'parent.php';
use Animals\Animal as Animal;
use mammals\Cheetah as Cheetah;
$cheetah_one = new Cheetah();
$cheetah_one->name = 'Blur';
echo "Hello! My name is " . $cheetah_one->getName();
?>
I'm using MAMP to run the code, and the following error keeps coming up: Cannot declare class Animals\Animal, because the name is already in use in /path/to/file/parent.php on line 4. All tips are appreciated.
Main.php does not need to include parent.php, as extended-classes.php already includes it. Alternatively, you can use include_once or require_once instead of include.
For including classes and constants , it's better to use
include_once or require_once
No more errors on re-declaring classes will thrown.
For me its working by using.
require_once 'extended-classes.php';
require_once 'parent.php';
it's due to including file again and again
Related
I have this file root/core/Router.php
<?php
namespace Core;
class Router {
protected $url;
protected $controller;
private function parseURL() {
// threat the $this->url; for example ["r", "product"]
}
private function request() {
$this->controller = Controller::get($this->url[1]);
}
public function __construct() {
$this->parseURL();
$this->request();
}
}
?>
then file root/core/Controller.php
<?php
namespace Core;
class Controller {
public static function model($name, $params = []) {
$model = "\\Model\\$name";
return new $model($params);
}
public static function view($name, $params = []) {
require_once APP_DIR . "view/" . $name . ".php";
}
public static function get($name, $params = []) {
require_once APP_DIR . "controller/" . $name . ".php";
$name = "\\Controller\\$name";
return new $name($params);
}
}
?>
then root/controler/Product.php
<?php
namespace Controller;
use Core\Controller;
use Model\Product;
class Product {
public function get() {
$ret['state'] = 510;
$productModel = new Product;
$products = $productModel->getAll();
if(isset($products)) {
$ret['products'] = $products;
$ret['state'] = 200;
}
return $ret;
}
}
?>
then file root/model/Product.php
<?php
namespace Model;
class Product {
public function add($values) {
return Database::insert("product", $values);
}
}
?>
and root/core/Model.php
<?php
namespace Core;
class Model {
protected $table = null;
public function getAll() {
// some code to collect data
}
}
?>
What i want to achive is that every Controller in root/controller/*.php able to load any Model in root/model/*.php but class inside root/model/*.php must able to access (inheritance/extends) the Model class inside root/core/Model.php i firstly asked on chatGPT for some AI Generated answer, that the reason why i get this far.
Then i get this error, when the AI keep giving the same answer.
Fatal error: Cannot declare class Controller\Product because the name is already in use in C:\xampp\htdocs\app\shop\controller\Product.php on line 6
I actually realize that the simple way probably with naming the class so ther no conflict between it but i became aware how to properly using the namespace if its such features in php. Those files loaded without any autoloader, so i just require_once each file in root/init.php file.
I read few documentations but hard to implement in multiple files and directorys.
I Apreciate any feedback, thanks
I have file init.php:
<?php
require_once 'config.php';
init::load();
?>
with config.php:
<?php
$config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>
A class with name something.php:
<?php
class something{
public function __contruct(){}
public function doIt(){
global $config;
var_dump($config); // NULL
}
}
?>
Why is it null?
In php.net, they told me that I can access but in reality is not .
I tried but have no idea.
I am using php 5.5.9.
The variable $config in config.php is not global.
To make it a global variable, which i do NOT suggest you have to write the magic word global in front of it.
I would suggest you to read superglobal variables.
And a little bit of variable scopes.
What I would suggest is to make a class which handles you this.
That should look something like
class Config
{
static $config = array ('something' => 1);
static function get($name, $default = null)
{
if (isset (self::$config[$name])) {
return self::$config[$name];
} else {
return $default;
}
}
}
Config::get('something'); // returns 1;
Use Singleton Pattern like this
<?php
class Configs {
protected static $_instance;
private $configs =[];
private function __construct() {
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
private function __clone() {
}
private function __wakeup() {
}
public function setConfigs($configs){
$this->configs = $configs;
}
public function getConfigs(){
return $this->configs;
}
}
Configs::getInstance()->setConfigs(['db'=>'abc','host'=>'xxx.xxx.xxx.xxxx']);
class Something{
public function __contruct(){}
public function doIt(){
return Configs::getInstance()->getConfigs();
}
}
var_dump((new Something)->doIt());
Include the file like this:
include("config.php");
class something{ ..
and print the array as var_dump($config); no need of global.
Change your class a bit to pass a variable on the constructor.
<?php
class something{
private $config;
public function __contruct($config){
$this->config = $config;
}
public function doIt(){
var_dump($this->config); // NULL
}
}
?>
Then, if you
include config.php
include yourClassFile.php
and do,
<?php
$my_class = new something($config);
$my_class->doIt();
?>
It should work.
Note: It is always good not to use Globals (in a place where we could avoid them)
class A{
public $name;
public function __construct() {
$this->name = 'first';
}
public function test1(){
if(!empty($_POST["name"]))
{
$name = 'second';
}
echo $name;
}
$f = new A;
$f->test1();
Why don't we get first and how set right default value variable $name only for class A?
I would be grateful for any help.
You can use a constructor to set the initial values (or pretty much do anything for that matter) as you need to like this:
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
}
Then you can use these default values in your other functions.
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
public function test1($inputName)
{
if(!empty($inputName))
{
$this->name=$inputName;
}
echo "The name is ".$this->name."\r\n";
}
}
$ex=new example();
$ex->test1(" "); // prints first.
$ex->test1("Bobby"); // prints Bobby
$ex->test1($_POST["name"]); // works as you expected it to.
you have two options to set the default values for the class attributes:
Option 1: set at the parameter level.
class A
{
public $name = "first";
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
Option 2: the magic method __construct() always being executed each time that you create a new instance.
class A
{
public $name;
public function __construct()
{
$this->name = 'first';
}
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
Use isset() to assign a default to a variable that may already have a value:
if (! isset($cars)) {
$cars = $default_cars;
}
Use the ternary (a ? b : c) operator to give a new variable a (possibly default) value:
$cars = isset($_GET['cars']) ? $_GET['cars'] : $default_cars;
I have Apache running on port 81. My project folder is MyPhpProject. Inside it I have 2 folders: Domain and Testing.
In Domain folder I have 3 PHP files:
BaseDomain.php which contains an abstract class BaseDomain
Location.php which contains a concrete class Location inherited from BaseDomain
Employee.php which contains a concrete class Employee inherited from BaseDomain
Employee class has a reference of Location class.
This is the BaseDomain.php:
<?php
abstract class BaseDomain {
}
?>
This is the Location.php:
<?php
$returnRequire = require 'BaseDomain.php';
class Location extends BaseDomain {
private $locationIdInt;
private $codeNameString;
private $descString;
public function setLocationId($locationId) {
$this->locationIdInt = $locationId;
}
public function getLocationId() {
return $this->locationIdInt;
}
public function setCodeName($codeName) {
$this->codeNameString = $codeName;
}
public function getCodeName() {
return $this->codeNameString;
}
public function setDesc($desc) {
$this->descString = $desc;
}
public function getDesc() {
return $this->descString;
}
}
?>
This is Employee.php:
<?php
$returnRequire = require 'BaseDomain.php';
class Employee extends BaseDomain {
private $employeeIdString;
private $locationObject;
public function setEmployeeId($employeeId) {
$this->employeeIdString = $employeeId;
}
public function getEmployeeId() {
return $this->employeeIdString;
}
public function setLocation($location) {
$this->locationObject = $location;
}
public function getLocation() {
return $this->locationObject;
}
}
?>
Now in the Testing folder I created a Test_Employee.php and this is its code:
<?php
set_include_path('../Domain');
$getIncludePath = get_include_path();
echo "getIncludePath = " . $getIncludePath;
echo "<br>";
$returnRequire1 = require 'Location.php';
echo "returnRequire for Location.php = " . $returnRequire1;
echo "<br>";
$returnRequire2 = require 'Employee.php';
echo "returnRequire for Employee.php = " . $returnRequire2;
echo "<br>";
?>
When I try to run it http://localhost:81/MyPhpProject/Testing/Test_Employee.php I got a fatal error regarding cannot redeclare BaseDomain class. This is what I see in browser:
getIncludePath = ../Domain
returnRequire for Location.php = 1
Fatal error: Cannot redeclare class BaseDomain in C:\Program Files
(x86)\Apache Software
Foundation\Apache2.2\htdocs\MyPhpProject\Domain\BaseDomain.php on line
2
I have not created BaseDomain class more than once. So this error is bizarre. Can somebody please explain why I am getting error message? And how to fix it.
Thanks for your time.
The line $returnRequire1 = require 'Location.php'; loads Location.php, which in turns loads BaseDomain.php in the line $returnRequire = require 'BaseDomain.php';. Then, the line $returnRequire2 = require 'Employee.php'; loads Employee.php, which loads (again) BaseDomain.php (the line $returnRequire = require 'BaseDomain.php';). The second load of BaseDomain.php causes php to try to redefine the BaseDomain class, which is no allowed.
The easiest way to solve this problem is to change your require calls to require_once. This will ensure that each file is loaded exactly once per run, which will prevent the error you are experiencing.
BaseDomain.php:
<?php
abstract class BaseDomain {
}
?>
Location.php
<?php
class Location extends BaseDomain {
private $locationIdInt;
private $codeNameString;
private $descString;
public function setLocationId($locationId) {
$this->locationIdInt = $locationId;
}
public function getLocationId() {
return $this->locationIdInt;
}
public function setCodeName($codeName) {
$this->codeNameString = $codeName;
}
public function getCodeName() {
return $this->codeNameString;
}
public function setDesc($desc) {
$this->descString = $desc;
}
public function getDesc() {
return $this->descString;
}
}
?>
Employee.php:
<?php
class Employee extends BaseDomain {
private $employeeIdString;
private $locationObject;
public function setEmployeeId($employeeId) {
$this->employeeIdString = $employeeId;
}
public function getEmployeeId() {
return $this->employeeIdString;
}
public function setLocation($location) {
$this->locationObject = $location;
}
public function getLocation() {
return $this->locationObject;
}
}
?>
Test_Employee.php
<?php
set_include_path(__DIR__.'/MyPhpProject/Domain');
require 'BaseDomain.php';
$getIncludePath = get_include_path();
echo "getIncludePath = " . $getIncludePath;
echo "<br>";
$returnRequire1 = require 'Location.php';
echo "returnRequire for Location.php = " . $returnRequire1;
echo "<br>";
$returnRequire2 = require 'Employee.php';
echo "returnRequire for Employee.php = " . $returnRequire2;
echo "<br>";
?>
I have this code:
//config.php
$EXAMPLE['try1'] = "...." ;
$EXAMPLE['try2'] = "...." ;
So, i have another file with a php class:
class try {
public function __construct() {
if($this->try1() && $this->try2()){
return true;
}
}
public function try1(){
require_once 'config.php' ;
echo $EXAMPLE['try1'];
return true;
}
public function try2(){
require_once 'config.php' ;
echo $EXAMPLE['try2'];
return true;
}
}
But in my case, $EXAMPLE['try1'] is ..... , but $EXAMPLE['try2'] is null... why? I've tried to include require_once 'config.php' ; on top page, and add after global $EXAMPLE; , but $EXAMPLE is ever null, why?
Use require, not require_once. Otherwise, if you load the file in one function, it won't be loaded in the other function, so it won't get the variables.
It would be better to require the function outside the functions entirely. Then declare $EXAMPLE as a global variable.
require_once 'config.php';
class try {
public function __construct() {
if($this->try1() && $this->try2()){
return true;
}
}
public function try1(){
global $EXAMPLE
echo $EXAMPLE['try1'];
return true;
}
public function try2(){
global $EXAMPLE
echo $EXAMPLE['try2'];
return true;
}
}
Require your file inside __construct method. So require once requires file once in try1 method.
class try {
private $_example = array();
public function __construct() {
require_once 'config.php';
$this->_example = $EXAMPLE;
return $this->try1() && $this->try2();
}
public function try1(){
echo $this->_example['try1'];
return true;
}
public function try2(){
echo $this->_example['try2'];
return true;
}
}