Dynamic class usage in PHP












1















I am writing a program which processes geographical coordinates of a city and I want to randomly select my city in each run; the process for all cities are the same.



I have a PHP class for each city which contains geographical coordinates of it; for example:



<?php
namespace UtilityLocations;
class Tehran
{
const MIN_LAT = 35.325;
const MAX_LAT = 35.390;
const MIN_LNG = 51.165;
const MAX_LNG = 51.230;
}


In another PHP file I make use of the class as:



use UtilityLocationsTehran;
use UtilityLocationsKaraj;
...
protected function MyProcessingMethod () {
...
$city = Faker::create()->randomElement(array("Tehran", "Karaj"));
echo $city::MIN_LAT;
...
}
...


If it helps, the above mentioned file is a CodeCeption Cest and MyProcessingMethod is used as a DataProvider. When I run my tests using codecept run scenarios/MyCest.php, I get this error:



PHP Fatal error:  Uncaught Error: Class 'Tehran' not found in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php:190
Stack trace:
#0 [internal function]: MyCest->MyProcessingMethod()
#1 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Util/ReflectionHelper.php(47): ReflectionMethod->invokeArgs(Object(MyCest), Array)
#2 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader/Cest.php(65): CodeceptionUtilReflectionHelper::invokePrivateMethod(Object(MyCest), Object(ReflectionMethod))
#3 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader.php(109): CodeceptionTestLoaderCest->loadTests('/home/zeinab/Ph...')
#4 /home/zeinab/PhpstormPro in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php on line 190


I've read PHP official documentations on this type of usage, but all examples there were using the classes that are defined inside destination file.



I also tried this:



$city =  Faker::create()->randomElement(array(Tehran::class, Karaj::class));
echo $city::MIN_LAT;


But I got the same error.



Is there anyway to do what I want to?



EDIT 1:
I have put the path to the classes in psr-4 tag of my composer.json:



"autoload": {
"psr-4": {
"Utility\": "Utility/"
}
}


It seems there is no problem in loading the classes, since using them directly works fine. For example the following code is doing great:



echo Tehran::MIN_LAT;









share|improve this question

























  • where do you include those classes? I see use - but no require_once before it - or PSR4 autoloader? Also, wouldn't it better to have one class called City and have a bunch of properties for that got via a db ID?

    – treyBake
    Jan 2 at 9:06











  • you can see this question and answers instantiate class with variables

    – Ali Ghalambaz
    Jan 2 at 9:10











  • @treyBake, please review my edit.

    – Zeinab Abbasimazar
    Jan 2 at 10:09
















1















I am writing a program which processes geographical coordinates of a city and I want to randomly select my city in each run; the process for all cities are the same.



I have a PHP class for each city which contains geographical coordinates of it; for example:



<?php
namespace UtilityLocations;
class Tehran
{
const MIN_LAT = 35.325;
const MAX_LAT = 35.390;
const MIN_LNG = 51.165;
const MAX_LNG = 51.230;
}


In another PHP file I make use of the class as:



use UtilityLocationsTehran;
use UtilityLocationsKaraj;
...
protected function MyProcessingMethod () {
...
$city = Faker::create()->randomElement(array("Tehran", "Karaj"));
echo $city::MIN_LAT;
...
}
...


If it helps, the above mentioned file is a CodeCeption Cest and MyProcessingMethod is used as a DataProvider. When I run my tests using codecept run scenarios/MyCest.php, I get this error:



PHP Fatal error:  Uncaught Error: Class 'Tehran' not found in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php:190
Stack trace:
#0 [internal function]: MyCest->MyProcessingMethod()
#1 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Util/ReflectionHelper.php(47): ReflectionMethod->invokeArgs(Object(MyCest), Array)
#2 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader/Cest.php(65): CodeceptionUtilReflectionHelper::invokePrivateMethod(Object(MyCest), Object(ReflectionMethod))
#3 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader.php(109): CodeceptionTestLoaderCest->loadTests('/home/zeinab/Ph...')
#4 /home/zeinab/PhpstormPro in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php on line 190


I've read PHP official documentations on this type of usage, but all examples there were using the classes that are defined inside destination file.



I also tried this:



$city =  Faker::create()->randomElement(array(Tehran::class, Karaj::class));
echo $city::MIN_LAT;


But I got the same error.



Is there anyway to do what I want to?



EDIT 1:
I have put the path to the classes in psr-4 tag of my composer.json:



"autoload": {
"psr-4": {
"Utility\": "Utility/"
}
}


It seems there is no problem in loading the classes, since using them directly works fine. For example the following code is doing great:



echo Tehran::MIN_LAT;









share|improve this question

























  • where do you include those classes? I see use - but no require_once before it - or PSR4 autoloader? Also, wouldn't it better to have one class called City and have a bunch of properties for that got via a db ID?

    – treyBake
    Jan 2 at 9:06











  • you can see this question and answers instantiate class with variables

    – Ali Ghalambaz
    Jan 2 at 9:10











  • @treyBake, please review my edit.

    – Zeinab Abbasimazar
    Jan 2 at 10:09














1












1








1








I am writing a program which processes geographical coordinates of a city and I want to randomly select my city in each run; the process for all cities are the same.



I have a PHP class for each city which contains geographical coordinates of it; for example:



<?php
namespace UtilityLocations;
class Tehran
{
const MIN_LAT = 35.325;
const MAX_LAT = 35.390;
const MIN_LNG = 51.165;
const MAX_LNG = 51.230;
}


In another PHP file I make use of the class as:



use UtilityLocationsTehran;
use UtilityLocationsKaraj;
...
protected function MyProcessingMethod () {
...
$city = Faker::create()->randomElement(array("Tehran", "Karaj"));
echo $city::MIN_LAT;
...
}
...


If it helps, the above mentioned file is a CodeCeption Cest and MyProcessingMethod is used as a DataProvider. When I run my tests using codecept run scenarios/MyCest.php, I get this error:



PHP Fatal error:  Uncaught Error: Class 'Tehran' not found in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php:190
Stack trace:
#0 [internal function]: MyCest->MyProcessingMethod()
#1 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Util/ReflectionHelper.php(47): ReflectionMethod->invokeArgs(Object(MyCest), Array)
#2 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader/Cest.php(65): CodeceptionUtilReflectionHelper::invokePrivateMethod(Object(MyCest), Object(ReflectionMethod))
#3 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader.php(109): CodeceptionTestLoaderCest->loadTests('/home/zeinab/Ph...')
#4 /home/zeinab/PhpstormPro in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php on line 190


I've read PHP official documentations on this type of usage, but all examples there were using the classes that are defined inside destination file.



I also tried this:



$city =  Faker::create()->randomElement(array(Tehran::class, Karaj::class));
echo $city::MIN_LAT;


But I got the same error.



Is there anyway to do what I want to?



EDIT 1:
I have put the path to the classes in psr-4 tag of my composer.json:



"autoload": {
"psr-4": {
"Utility\": "Utility/"
}
}


It seems there is no problem in loading the classes, since using them directly works fine. For example the following code is doing great:



echo Tehran::MIN_LAT;









share|improve this question
















I am writing a program which processes geographical coordinates of a city and I want to randomly select my city in each run; the process for all cities are the same.



I have a PHP class for each city which contains geographical coordinates of it; for example:



<?php
namespace UtilityLocations;
class Tehran
{
const MIN_LAT = 35.325;
const MAX_LAT = 35.390;
const MIN_LNG = 51.165;
const MAX_LNG = 51.230;
}


In another PHP file I make use of the class as:



use UtilityLocationsTehran;
use UtilityLocationsKaraj;
...
protected function MyProcessingMethod () {
...
$city = Faker::create()->randomElement(array("Tehran", "Karaj"));
echo $city::MIN_LAT;
...
}
...


If it helps, the above mentioned file is a CodeCeption Cest and MyProcessingMethod is used as a DataProvider. When I run my tests using codecept run scenarios/MyCest.php, I get this error:



PHP Fatal error:  Uncaught Error: Class 'Tehran' not found in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php:190
Stack trace:
#0 [internal function]: MyCest->MyProcessingMethod()
#1 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Util/ReflectionHelper.php(47): ReflectionMethod->invokeArgs(Object(MyCest), Array)
#2 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader/Cest.php(65): CodeceptionUtilReflectionHelper::invokePrivateMethod(Object(MyCest), Object(ReflectionMethod))
#3 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader.php(109): CodeceptionTestLoaderCest->loadTests('/home/zeinab/Ph...')
#4 /home/zeinab/PhpstormPro in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php on line 190


I've read PHP official documentations on this type of usage, but all examples there were using the classes that are defined inside destination file.



I also tried this:



$city =  Faker::create()->randomElement(array(Tehran::class, Karaj::class));
echo $city::MIN_LAT;


But I got the same error.



Is there anyway to do what I want to?



EDIT 1:
I have put the path to the classes in psr-4 tag of my composer.json:



"autoload": {
"psr-4": {
"Utility\": "Utility/"
}
}


It seems there is no problem in loading the classes, since using them directly works fine. For example the following code is doing great:



echo Tehran::MIN_LAT;






php class codeception






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 10:08







Zeinab Abbasimazar

















asked Jan 2 at 9:03









Zeinab AbbasimazarZeinab Abbasimazar

3,57564381




3,57564381













  • where do you include those classes? I see use - but no require_once before it - or PSR4 autoloader? Also, wouldn't it better to have one class called City and have a bunch of properties for that got via a db ID?

    – treyBake
    Jan 2 at 9:06











  • you can see this question and answers instantiate class with variables

    – Ali Ghalambaz
    Jan 2 at 9:10











  • @treyBake, please review my edit.

    – Zeinab Abbasimazar
    Jan 2 at 10:09



















  • where do you include those classes? I see use - but no require_once before it - or PSR4 autoloader? Also, wouldn't it better to have one class called City and have a bunch of properties for that got via a db ID?

    – treyBake
    Jan 2 at 9:06











  • you can see this question and answers instantiate class with variables

    – Ali Ghalambaz
    Jan 2 at 9:10











  • @treyBake, please review my edit.

    – Zeinab Abbasimazar
    Jan 2 at 10:09

















where do you include those classes? I see use - but no require_once before it - or PSR4 autoloader? Also, wouldn't it better to have one class called City and have a bunch of properties for that got via a db ID?

– treyBake
Jan 2 at 9:06





where do you include those classes? I see use - but no require_once before it - or PSR4 autoloader? Also, wouldn't it better to have one class called City and have a bunch of properties for that got via a db ID?

– treyBake
Jan 2 at 9:06













you can see this question and answers instantiate class with variables

– Ali Ghalambaz
Jan 2 at 9:10





you can see this question and answers instantiate class with variables

– Ali Ghalambaz
Jan 2 at 9:10













@treyBake, please review my edit.

– Zeinab Abbasimazar
Jan 2 at 10:09





@treyBake, please review my edit.

– Zeinab Abbasimazar
Jan 2 at 10:09












2 Answers
2






active

oldest

votes


















0














I created this code snippet for example purposes - so it may not fully reflect your methods but the answer is the principle :)



<?php
# create our city classes
class Brighton
{
const X = 1;
const Y = 2;
}

class London
{
const X = 3;
const Y = 4;
}

# create our get city class
class Foo
{
public function getCity()
{
$possibleCities = ['Brighton', 'London', 'Birmingham']; # add a city that's not a class for testing
$city = rand(0, count($possibleCities) -1);

return $possibleCities[$city];
}
}

# init foo
$foo = new Foo();
$city = $foo->getCity(); # get city

# check if class exists, if it does, init it
$cityClass = (class_exists($city) ? new $city() : null);

# check if class is empty - if it isn't echo CONST X
echo (!empty($cityClass) ? $cityClass::X : $city. ' class not found');


How to include the classes (if they're in separate files):



Imagine the tree is:



|-app
|-----core
|---------city
|-------------Brighton.php
|-------------London.php
|-----Foo.php


In Foo.php



<?php
require_once 'city/Brighton.php';
require_once 'city/London.php';

use CityBrighton;
use CityLondon;

# etc. etc


And then Brighton.php and London.php have the namespace of City:



<?php
namespace City;

class Brighton
{} # etc





share|improve this answer


























  • This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

    – Zeinab Abbasimazar
    Jan 2 at 10:50











  • @ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

    – treyBake
    Jan 2 at 10:51











  • Where should I put that? Would you please help me on that?

    – Zeinab Abbasimazar
    Jan 2 at 11:25











  • before the use - I'll quickly edit my answer

    – treyBake
    Jan 2 at 11:27











  • I have got this error: failed to open stream: No such file or directory

    – Zeinab Abbasimazar
    Jan 2 at 11:42





















0














add loader to first line of your code :



function loader($className)
{
$fileName = str_replace('\', '/', $className) . '.php';
require_once $fileName;
}
spl_autoload_register('loader');


then use namespaces like directory structures :




Ahvaz.php in app/core/city directory




namespace appcorecity;
class Ahvaz
{
//...
}


when you load a class Ahvaz.php like this



$var = new Ahvaz();


you need to add use appcorecity;



then you have :



use appcorecity;
$var = new Ahvaz();


it will include Ahvaz.php from app/core/city directory






share|improve this answer


























  • I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

    – Zeinab Abbasimazar
    Jan 2 at 10:48











  • if you want access your classes from another files you can use __autoload function and(or) namespaces

    – Ali Ghalambaz
    Jan 2 at 12:04











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003612%2fdynamic-class-usage-in-php%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I created this code snippet for example purposes - so it may not fully reflect your methods but the answer is the principle :)



<?php
# create our city classes
class Brighton
{
const X = 1;
const Y = 2;
}

class London
{
const X = 3;
const Y = 4;
}

# create our get city class
class Foo
{
public function getCity()
{
$possibleCities = ['Brighton', 'London', 'Birmingham']; # add a city that's not a class for testing
$city = rand(0, count($possibleCities) -1);

return $possibleCities[$city];
}
}

# init foo
$foo = new Foo();
$city = $foo->getCity(); # get city

# check if class exists, if it does, init it
$cityClass = (class_exists($city) ? new $city() : null);

# check if class is empty - if it isn't echo CONST X
echo (!empty($cityClass) ? $cityClass::X : $city. ' class not found');


How to include the classes (if they're in separate files):



Imagine the tree is:



|-app
|-----core
|---------city
|-------------Brighton.php
|-------------London.php
|-----Foo.php


In Foo.php



<?php
require_once 'city/Brighton.php';
require_once 'city/London.php';

use CityBrighton;
use CityLondon;

# etc. etc


And then Brighton.php and London.php have the namespace of City:



<?php
namespace City;

class Brighton
{} # etc





share|improve this answer


























  • This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

    – Zeinab Abbasimazar
    Jan 2 at 10:50











  • @ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

    – treyBake
    Jan 2 at 10:51











  • Where should I put that? Would you please help me on that?

    – Zeinab Abbasimazar
    Jan 2 at 11:25











  • before the use - I'll quickly edit my answer

    – treyBake
    Jan 2 at 11:27











  • I have got this error: failed to open stream: No such file or directory

    – Zeinab Abbasimazar
    Jan 2 at 11:42


















0














I created this code snippet for example purposes - so it may not fully reflect your methods but the answer is the principle :)



<?php
# create our city classes
class Brighton
{
const X = 1;
const Y = 2;
}

class London
{
const X = 3;
const Y = 4;
}

# create our get city class
class Foo
{
public function getCity()
{
$possibleCities = ['Brighton', 'London', 'Birmingham']; # add a city that's not a class for testing
$city = rand(0, count($possibleCities) -1);

return $possibleCities[$city];
}
}

# init foo
$foo = new Foo();
$city = $foo->getCity(); # get city

# check if class exists, if it does, init it
$cityClass = (class_exists($city) ? new $city() : null);

# check if class is empty - if it isn't echo CONST X
echo (!empty($cityClass) ? $cityClass::X : $city. ' class not found');


How to include the classes (if they're in separate files):



Imagine the tree is:



|-app
|-----core
|---------city
|-------------Brighton.php
|-------------London.php
|-----Foo.php


In Foo.php



<?php
require_once 'city/Brighton.php';
require_once 'city/London.php';

use CityBrighton;
use CityLondon;

# etc. etc


And then Brighton.php and London.php have the namespace of City:



<?php
namespace City;

class Brighton
{} # etc





share|improve this answer


























  • This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

    – Zeinab Abbasimazar
    Jan 2 at 10:50











  • @ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

    – treyBake
    Jan 2 at 10:51











  • Where should I put that? Would you please help me on that?

    – Zeinab Abbasimazar
    Jan 2 at 11:25











  • before the use - I'll quickly edit my answer

    – treyBake
    Jan 2 at 11:27











  • I have got this error: failed to open stream: No such file or directory

    – Zeinab Abbasimazar
    Jan 2 at 11:42
















0












0








0







I created this code snippet for example purposes - so it may not fully reflect your methods but the answer is the principle :)



<?php
# create our city classes
class Brighton
{
const X = 1;
const Y = 2;
}

class London
{
const X = 3;
const Y = 4;
}

# create our get city class
class Foo
{
public function getCity()
{
$possibleCities = ['Brighton', 'London', 'Birmingham']; # add a city that's not a class for testing
$city = rand(0, count($possibleCities) -1);

return $possibleCities[$city];
}
}

# init foo
$foo = new Foo();
$city = $foo->getCity(); # get city

# check if class exists, if it does, init it
$cityClass = (class_exists($city) ? new $city() : null);

# check if class is empty - if it isn't echo CONST X
echo (!empty($cityClass) ? $cityClass::X : $city. ' class not found');


How to include the classes (if they're in separate files):



Imagine the tree is:



|-app
|-----core
|---------city
|-------------Brighton.php
|-------------London.php
|-----Foo.php


In Foo.php



<?php
require_once 'city/Brighton.php';
require_once 'city/London.php';

use CityBrighton;
use CityLondon;

# etc. etc


And then Brighton.php and London.php have the namespace of City:



<?php
namespace City;

class Brighton
{} # etc





share|improve this answer















I created this code snippet for example purposes - so it may not fully reflect your methods but the answer is the principle :)



<?php
# create our city classes
class Brighton
{
const X = 1;
const Y = 2;
}

class London
{
const X = 3;
const Y = 4;
}

# create our get city class
class Foo
{
public function getCity()
{
$possibleCities = ['Brighton', 'London', 'Birmingham']; # add a city that's not a class for testing
$city = rand(0, count($possibleCities) -1);

return $possibleCities[$city];
}
}

# init foo
$foo = new Foo();
$city = $foo->getCity(); # get city

# check if class exists, if it does, init it
$cityClass = (class_exists($city) ? new $city() : null);

# check if class is empty - if it isn't echo CONST X
echo (!empty($cityClass) ? $cityClass::X : $city. ' class not found');


How to include the classes (if they're in separate files):



Imagine the tree is:



|-app
|-----core
|---------city
|-------------Brighton.php
|-------------London.php
|-----Foo.php


In Foo.php



<?php
require_once 'city/Brighton.php';
require_once 'city/London.php';

use CityBrighton;
use CityLondon;

# etc. etc


And then Brighton.php and London.php have the namespace of City:



<?php
namespace City;

class Brighton
{} # etc






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 2 at 11:29

























answered Jan 2 at 10:21









treyBaketreyBake

3,48531237




3,48531237













  • This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

    – Zeinab Abbasimazar
    Jan 2 at 10:50











  • @ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

    – treyBake
    Jan 2 at 10:51











  • Where should I put that? Would you please help me on that?

    – Zeinab Abbasimazar
    Jan 2 at 11:25











  • before the use - I'll quickly edit my answer

    – treyBake
    Jan 2 at 11:27











  • I have got this error: failed to open stream: No such file or directory

    – Zeinab Abbasimazar
    Jan 2 at 11:42





















  • This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

    – Zeinab Abbasimazar
    Jan 2 at 10:50











  • @ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

    – treyBake
    Jan 2 at 10:51











  • Where should I put that? Would you please help me on that?

    – Zeinab Abbasimazar
    Jan 2 at 11:25











  • before the use - I'll quickly edit my answer

    – treyBake
    Jan 2 at 11:27











  • I have got this error: failed to open stream: No such file or directory

    – Zeinab Abbasimazar
    Jan 2 at 11:42



















This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

– Zeinab Abbasimazar
Jan 2 at 10:50





This code won't work if I put Brighton and London classes in another file. My issue is that I want to use classes from other files

– Zeinab Abbasimazar
Jan 2 at 10:50













@ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

– treyBake
Jan 2 at 10:51





@ZeinabAbbasimazar have you tried using a manual require_once of the classes? If that works with require_once then there's something pos wrong with your autoloader

– treyBake
Jan 2 at 10:51













Where should I put that? Would you please help me on that?

– Zeinab Abbasimazar
Jan 2 at 11:25





Where should I put that? Would you please help me on that?

– Zeinab Abbasimazar
Jan 2 at 11:25













before the use - I'll quickly edit my answer

– treyBake
Jan 2 at 11:27





before the use - I'll quickly edit my answer

– treyBake
Jan 2 at 11:27













I have got this error: failed to open stream: No such file or directory

– Zeinab Abbasimazar
Jan 2 at 11:42







I have got this error: failed to open stream: No such file or directory

– Zeinab Abbasimazar
Jan 2 at 11:42















0














add loader to first line of your code :



function loader($className)
{
$fileName = str_replace('\', '/', $className) . '.php';
require_once $fileName;
}
spl_autoload_register('loader');


then use namespaces like directory structures :




Ahvaz.php in app/core/city directory




namespace appcorecity;
class Ahvaz
{
//...
}


when you load a class Ahvaz.php like this



$var = new Ahvaz();


you need to add use appcorecity;



then you have :



use appcorecity;
$var = new Ahvaz();


it will include Ahvaz.php from app/core/city directory






share|improve this answer


























  • I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

    – Zeinab Abbasimazar
    Jan 2 at 10:48











  • if you want access your classes from another files you can use __autoload function and(or) namespaces

    – Ali Ghalambaz
    Jan 2 at 12:04
















0














add loader to first line of your code :



function loader($className)
{
$fileName = str_replace('\', '/', $className) . '.php';
require_once $fileName;
}
spl_autoload_register('loader');


then use namespaces like directory structures :




Ahvaz.php in app/core/city directory




namespace appcorecity;
class Ahvaz
{
//...
}


when you load a class Ahvaz.php like this



$var = new Ahvaz();


you need to add use appcorecity;



then you have :



use appcorecity;
$var = new Ahvaz();


it will include Ahvaz.php from app/core/city directory






share|improve this answer


























  • I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

    – Zeinab Abbasimazar
    Jan 2 at 10:48











  • if you want access your classes from another files you can use __autoload function and(or) namespaces

    – Ali Ghalambaz
    Jan 2 at 12:04














0












0








0







add loader to first line of your code :



function loader($className)
{
$fileName = str_replace('\', '/', $className) . '.php';
require_once $fileName;
}
spl_autoload_register('loader');


then use namespaces like directory structures :




Ahvaz.php in app/core/city directory




namespace appcorecity;
class Ahvaz
{
//...
}


when you load a class Ahvaz.php like this



$var = new Ahvaz();


you need to add use appcorecity;



then you have :



use appcorecity;
$var = new Ahvaz();


it will include Ahvaz.php from app/core/city directory






share|improve this answer















add loader to first line of your code :



function loader($className)
{
$fileName = str_replace('\', '/', $className) . '.php';
require_once $fileName;
}
spl_autoload_register('loader');


then use namespaces like directory structures :




Ahvaz.php in app/core/city directory




namespace appcorecity;
class Ahvaz
{
//...
}


when you load a class Ahvaz.php like this



$var = new Ahvaz();


you need to add use appcorecity;



then you have :



use appcorecity;
$var = new Ahvaz();


it will include Ahvaz.php from app/core/city directory







share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 2 at 12:14

























answered Jan 2 at 9:12









Ali GhalambazAli Ghalambaz

36025




36025













  • I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

    – Zeinab Abbasimazar
    Jan 2 at 10:48











  • if you want access your classes from another files you can use __autoload function and(or) namespaces

    – Ali Ghalambaz
    Jan 2 at 12:04



















  • I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

    – Zeinab Abbasimazar
    Jan 2 at 10:48











  • if you want access your classes from another files you can use __autoload function and(or) namespaces

    – Ali Ghalambaz
    Jan 2 at 12:04

















I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

– Zeinab Abbasimazar
Jan 2 at 10:48





I don't want to put methods to return constants. BTW, this code won't work if I put my class in another file. My issue is that I want to use classes from other files.

– Zeinab Abbasimazar
Jan 2 at 10:48













if you want access your classes from another files you can use __autoload function and(or) namespaces

– Ali Ghalambaz
Jan 2 at 12:04





if you want access your classes from another files you can use __autoload function and(or) namespaces

– Ali Ghalambaz
Jan 2 at 12:04


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003612%2fdynamic-class-usage-in-php%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

A Topological Invariant for $pi_3(U(n))$