Can't access property from outside function PHP? - php

I am trying to access a property outside of a function in PHP, but it is not working?
<?php
class Bootstrap {
private $_url = null;
public function init() {
$this->_loadController();
}
public function getUrl() {
$url = (isset($_GET['url'])) ? $_GET['url'] : null;
$this->_url = explode('/', $_GET['url']);
}
public function _loadController() {
echo $this->_url[0];
}
}
If I echo $this->_url[0] in the method getUrl and then call it from my index page, I get the URL. While if I call it from the _loadController method, I just get a blank page. I did var_dump($this->_url) and got NULL.
My code in my index page is follows
<?php
include 'bootstrap.php';
$bootstrap = new Bootstrap();
$app = $bootstrap->init();
?>
Could someone help me out? Thanks!

You have the problem because, you did not call getUrl(), but in this method you set valueinto $_url. Change you code to this:
class Bootstrap {
private $_url = null;
public function init() {
$this->_loadController();
}
public function getUrl() {
$url = (isset($_GET['url'])) ? $_GET['url'] : null;
$this->_url = explode('/', $_GET['url']);
}
public function _loadController() {
$this-> getUrl(); // here you call getUrl()
echo $this->_url[0];
}
}
Or, you can use magic mathod to set the url into, here:
class Bootstrap {
private $_url = null;
public function init() {
$this->_loadController();
}
public function __construct() {
$url = (isset($_GET['url'])) ? $_GET['url'] : null;
$this->_url = explode('/', $_GET['url']);
}
public function _loadController() {
echo $this->_url[0];
}
}

Related

Get url action in Application child class

This function is in Application class > mvc > php
private function splitUrl()
{
if (isset($_GET['url'])) {
// split URL
$url = trim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
$this->url_controller = isset($url[0]) ? $url[0] : null;
$this->url_action = isset($url[1]) ? $url[1] : null;
unset($url[0], $url[1]);
$this->url_params = array_values($url);
}
}
New edit
I have this class
class Page extends Controller
{
public function __construct(){
//echo parent::splitUrl()->this->url_action;
echo parent::$this->url_action;
}
public function index()
{
// removed lins
}
}
How to get $this->url_action in extends functions ?
The field url_action should be protected (or public, but that's not recommend). So you can use this in child classes.
See below such as pseudoniem code:
In your parent:
class Foo
{
protected $url_action = 'something'; // or set it via setter
}
The child class:
class FooChild extends Foo // Now, child can access protected (and public) fields of its parent!
{
public function getFromParent()
{
return $this->url_action; // or what you want
}
}

Get Class to know a Variable

I'm facing a problem, I want the class Page to know the Variable '$format'.
// class1.php
<?php
include('./class2.php');
echo $format->getTest(); // returns :-) (declared in class2.php)
class Page {
PUBLIC function getText() {
return $format->getTest(); // returns Call to a member function getTest() on null
}
}
$page = new Page;
?>
// class2.php
<?php
class Format {
PUBLIC function getTest() {
return ":-)";
}
}
$format = new Format;
?>
Any suggestions/ideas?
EDIT:
I found a way: return $GLOBALS['format']->getTest();
But I dont like it, its so much to type. Any other way(s)?
Philip
Proper objective solution is to pass variable to constructor, setter or as argument to getText() method. Choose one you find most appropriate for your case.
Constructor
class Page
{
private $format;
public function __construct(Format $format)
{
$this->format = $format;
}
public function getText()
{
return $this->format->getTest();
}
}
$page = new Page($format);
echo $page->getText();
Setter
class Page
{
private $format;
public function setFormat(Format $format)
{
$this->format = $format;
}
public function getText()
{
return $this->format->getTest();
}
}
$page = new Page;
$page->setFormat($format);
echo $page->getText();
Argument
class Page
{
public function getText(Format $format)
{
return $format->getTest();
}
}
$page = new Page;
echo $page->getText($format);

php dynamic class methods - scope issue

Hello I'm trying to implement a url router in php something familiar to express.js
Here is the code I have so far.
class Router{
private $request;
private $request_params;
private $params_num;
private $paths;
public function __construct(){
$this->paths = array();
$this->request = strtolower($this->hookRequest());
if ($this->request != false){
$this->request_params = $this->hookRequestParams();
} else {
$this->request_params = array('home');
}
}
public function __destruct(){
foreach($this->paths as $key => $value){
if($this->getRequest() == $key){
$value();
}
}
}
public function get($path, $func){
$this->paths[$path] = $func;
}
private function hookRequest(){
return isset($_GET['req']) ? rtrim($_GET['req'], '/') : false;
}
private function hookRequestParams(){
$params = explode('/', $this->request);
$this->params_num = count($params);
return $params;
}
public function getRequest(){
return $this->request;
}
public function getRequestParams(){
return $this->request_params;
}
public function getPage(){
return $this->request_params[0];
}
public function getAction(){
if($this->params_num > 1){
return $this->request_params[1];
}
return false;
}
public function getActionParams(){
if($this->params_num > 2){
return $this->request_params[2];
}
return false;
}
}
This is used like this as you can imagine:
$router = new Router();
$router->get('index', function(){
echo 'index'; //index is being shown to the browser as expectd
echo $this->getPage(); // This does not work apparently
})
My issue is how could I execute $router methods from within the anonymous function?
As shown in this example with $this->getPAge();
Use a closure..
$router->get('index', function() use ($router) {
echo 'index';
echo $router->getPage();
})
If you define your Closure within your class, $this should be work.

using a static class with properties in php

I'm trying to get the selected language to appear in a link with the function buildMenu().
I would like to use it as a static function so I can call it in my header template. If I call the function in the init() function it all works fine, however, when I try to use it as a static function, nothing works anymore. I've tried everything I know, so it seems my knowledge of php ends there :)
Any of you got any tips? Thanks in advance!
class bootstrap {
static public $lang;
static public $class;
static public $method;
public function init(){
$url = isset($_GET['url']) ? $_GET['url'] : null;
$url = rtrim($url, '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
//Set values on startup
if($url[0] == NULL) {$url[0] = 'nl';}
if($url[1] == NULL) {$url[1] = 'index';}
if(isset($url[0])) {$this->lang = $url[0];}
if(isset($url[1])) {$this->class = $url[1];}
if(isset($url[2])) {$this->method = $url[2];}
$this->loadClass();
}
public function loadClass(){
$filename = 'libs/' . $this->class . '.php';
if(file_exists($filename)){
$newController = new $this->class($this->lang, $this->class, $this->method);
$newView = new view($this->lang, $this->class, $this->method);
} else {
$newclass = new error($this->lang, $this->class, $this->method);
}
}
public function buildMenu(){
echo '<li>Foto</li>';
}
/*
* Set paths
*/
public static function root(){
echo "http://localhost/testing/";
}
}
You are using the object operator (->) instead of the scope resolution operator (::) that is used to reference class constants and static properties or methods.
See here for an explanation of the static keyword and working with static properties.
Update your code to this:
class bootstrap{
static public $lang;
static public $class;
static public $method;
public function init(){
$url = isset($_GET['url']) ? $_GET['url'] : null;
$url = rtrim($url, '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
//Set values on startup
if($url[0] == NULL) {$url[0] = 'nl';}
if($url[1] == NULL) {$url[1] = 'index';}
if(isset($url[0])) {self::$lang = $url[0];}
if(isset($url[1])) {self::$class = $url[1];}
if(isset($url[2])) {self::$method = $url[2];}
$this->loadClass();
}
public function loadClass(){
$filename = 'libs/' . self::$class . '.php';
if(file_exists($filename)){
$newController = new self::$class(self::$lang, self::$class, self::$method);
$newView = new view(self::$lang, self::$class, self::$method);
} else {
$newclass = new error(self::$lang, self::$class, self::$method);
}
}
public static function buildMenu(){
echo '<li>Foto</li>';
}
public static function root(){
echo "http://localhost/testing/";
}
}
As #elclanrs has already mentioned, how about changing the buildMenu() method to
public static function buildMenu(){
echo '<li>Foto</li>';
}
You can then call it using bootstrap::buildMenu().

PHP MVC - Why is my request/router always going to home controller?

I've tried many fixes but for some reason my request and routing mechanisms in my framework aren't working properly. It's a multi-language site (en/fr) and I use mod_rewrite to get the language, class, method and an optional argument. My request.php sets the controller to languageController if the language isn't set, and it works (successfully echo "language" in controller). But, if the language is set, the controller that always ends up displaying is homeController despite that the uri is /en/about. I have no idea why this is happening and it's really frustrating me. Here's the problem code, help is appreciated.
Note: I haven't used namespaces as it is a small website that I just want to get up and running and there's no real need, although I plan to edit it to use namespaces in the future simply for the leaning.
relevant parts of index.php
//analyze request
$request = new Request($_GET); //breaks up the uri into an array
//routing
$router = new Router($request); //stores the requested uri in the router
$router->route(); //sets the proper route
//instancialize and execute the controller
$class = $router->getController();
$method = $router->getMethod();
$controller = new $class;
$controller->$method();
Request.php
class Request {
private $request;
public function __construct($uri) {
$this->request = $uri;
//if the language isn't selected
if($this->request['language']=="") {
$this->request['language'] = "language";
$this->request['class'] = "language";
$this->request['method'] = "index";
}
//else if the controller is not selected
else if($this->request['controller']=="") {
$this->request['class'] = "home";
$this->request['method'] = "index";
}
//stores the requested method
else if($this->request['method']=="") {
$this->request['method'] = "index";
}
//stores a value of false if there is no argument in the uri
if($this->request['arg']=="") {
$this->request['arg'] = false;
}
}
public function getLanguage() {
return $this->request['language'];
}
public function getClass() {
return $this->request['class'];
}
public function getMethod() {
return $this->request['method'];
}
public function getArgument() {
return $this->request['arg'];
}
}
Router.php
class Router {
private $language;
private $controller;
private $view;
private $method;
private $arg;
public function __construct(Request $request) { //given an instance of request, store it in local variables
$this->language = $request->getLanguage();
$this->controller = $request->getClass() . 'Controller';
$this->view = $request->getClass() . 'View';
$this->method = $request->getMethod();
$this->arg = $request->getArgument();
}
public function route() { //put the requested uri into forms we can deal with
if($this->language == "fr") { //compare it against url translation chart
//run all uri values through a chart that translates them from french to english if it finds a match
}
else { //it must be english
}
}
public function getLanguage() {
return $this->language;
}
public function getController() {
return $this->controller;
}
public function getView() {
return $this->view;
}
public function getMethod() {
return $this->method;
}
public function getArgument() {
return $this->arg;
}
}

Categories