is there something like with/end with (like in asp) for php?
especially for class objects it would be nice - asp syntax is like:
with myWeb
.init "myweb"
response.write .html
end with
thanks
No, there is no such thing in PHP : you have to write the full name of classes / objects / variables / whatever when you want to use them.
No, AFAIK.
Do you really find this syntax useful ?
No, but there is an alternative syntax for control structures that may interest you.
not sure im right but tryed my best to translate your example :/
<?php function write_block(){
echo '.html';
}
die(write_block());
?>
It's not exactly what you wanted, but you can do something similar with PHP references:
<?php
class A {
public $bar1 = 1;
public $bar2 = 2;
public $bar3 = 3;
}
class B {
public $foo;
}
class C {
public $foobar;
}
$myC = new C;
$myC->foobar = new B;
$myC->foobar->foo = new A;
print $myC->foobar->foo->bar1;
print $myC->foobar->foo->bar2;
print $myC->foobar->foo->bar3;
//Simpler with 'With...End With syntax:
//which might look something like:
//
// with ($myC->foobar->foo) //Note this is not valid PHP
// {
// print ->bar1; //Note this is not valid PHP
// print ->bar2; //Note this is not valid PHP
// print ->bar3; //Note this is not valid PHP
// }
//
//Fortunately, you can sort of do this using an object reference:
//
$obj =& $myC->foobar->foo;
print $obj->bar1;
print $obj->bar2;
print $obj->bar3;
unset ($obj);
?>
Related
Short Version: Why can't we access a function like this:
$b = "simple_print()";
$obj->$b;
Complete Version:
Suppose we have a class User defined like this:
class User {
public $name;
function simple_print() {
echo "Just Printing" . "<br>";
}
}
Now if a create an User object and set the name of it we can print its name using
$obj = new User;
$obj->name = "John";
echo $obj->name;
Although it is strange we also can do something like this in order to print "John":
$a = "name";
echo $obj->$a;
But we can't access a function using the same idea:
$b = "simple_print()";
$obj->$b;
Why? Shouldn't it work the same way?
Also, does anyone know what is it called? I tried to look for "accessing a member through a variable" and "using a method through a variable with the name of it" but I didn't find anything related to this.
Extra info: The version of PHP I'm using is: PHP version: 5.5.9-1ubuntu4.7
You were very close, but made a small logical mistake. Try this instead:
$b = 'simple_print';
$obj->$b();
This is because the method is accessed by it's name, which is simple_print, not simple_print(). The execution is triggered by the parenthesis, but that is not part of the name, so of how you access the method.
Here is a short example:
<?php
class Test
{
public function simple_print() {
echo "Hello world!\n";
}
}
$object = new Test;
$method = 'simple_print';
$object->$method();
As expected it creates the output Hello world! if executed on CLI.
Can non-anonymous functions in PHP using 'use' keyword? Or it is available for anonymous functions only.
Can I write a php file like this
// L.php
// assume $_texts is in this context..
$_language = null;
function L_init($language) use (&$_language)
{
$_language = $language;
}
function L($key) use ($_texts, $_language)
{
$_texts[$_language][$key];
}
So, another file can use it like this
// client.php
require_once 'L.php';
L_init('en');
echo L('GREETING'); // Will output localize string of key 'GREETING'
It is available for anonymous functions, but you can assign it to a variable:
$some_external_var = "World!";
$function = function() use($some_external_var){
echo "Hello ".$some_external_var;
};
Finally you can invoke it with:
call_user_func($function);
or just:
$function();
No you can't.
The code generate syntax errors.
Is it possible to call only the specific function from another file without including whole file???
There may be another functions in the file and don't need to render other function.
The short answer is: no, you can't.
The long answers is: yes, if you use OOP.
Split your functions into different files. Say you are making a game with a hero:
Walk.php
function walk($distance,speed){
//walk code
}
Die.php
function die(){
//game over
}
Hero.php
include 'Walk.php';
include 'Die.php';
class Hero(){
//hero that can walk & can die
}
You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.
One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.
In PHP it's not available to get only a little part of a file.
Maybe this is a ability to use only little parts of a file:
I have a class that calls "utilities". This I am using in my projects.
In my index.php
include("class.utilities.php")
$utilities = new utilities();
The file class.utilities.php
class utilities {
function __construct() {
}
public function thisIsTheFunction($a,$b)
{
$c = $a + $b;
return $c;
}
}
And then i can use the function
echo $utilities->thisIsTheFunction(3,4);
include a page lets say the function is GetPage and the variable is ID
<?php
require('page.php');
$id = ($_GET['id']);
if($id != '') {
getpage($id);
}
?>
now when you make the function
<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>
Can PHP namespaces contain variables? If so, how can this be accomplished?
No. You can set a variable after declaring a namespace, but variables will always exist in the global scope. They are never bound to namespaces. You can deduce that from the absence of any name resolution descriptions in
FAQ: things you need to know about namespaces (PHP 5 >= 5.3.0)
There would also be no allowed syntax to locate variables in a namespace.
print \namespace\$var; // syntax error
print "${namespace\\var}"; // "unexpected T_NS_SEPARATOR"
Try this
<?php
namespace App\login;
$p = 'login';
$test2 = '\App\\'.$p.'\\MyClass';
$test = new $test2;
No they cannot, as mario said.
To encapsulate variables use Classes. Polluting the global variable space should definitely be avoided.
Example
class_dbworker.php:
class DbWorker
{
//properties and method logic
}
class DbWorkerData
{
public static $hugerelationsmap = array(....);
public static ....
}
mainapp.php:
include_once 'class_dbworker.php';
print_r( DbWorkerData::$hugerelationsmap );
Example using namespaces
class_dbworker.php:
namespace staticdata;
class DbWorker
{
//properties and method logic
}
class DbWorkerData
{
public static $hugerelationsmap = array(....);
public static ....
}
mainapp.php:
include_once 'class_dbworker.php';
use staticdata as data;
print_r( \data\DbWorkerData::$hugerelationsmap );
It is not possible because $MYVARNAME is still in the global scope. Try following code.
namespace.php
<?php
namespace MYNAME;
use MYNAME as M;
const MYVAR = 'MYVARNAME';
${M\MYVAR} = date('Y');
echo $MYVARNAME; // PRINT YEAR
$MYVARNAME = 'X';
echo $MYVARNAME; // PRINT X
echo ${M\MYVAR} ; // PRINT X
include('file.php');
?>
file.php
<?php
${MYNAME\MYVAR}=date('Y');
echo $MYVARNAME; // PRINT YEAR
$MYVARNAME = 'X';
echo $MYVARNAME; // PRINT X
echo ${MYNAME\MYVAR}; // PRINT X
include('file2.php');
?>
file2.php
<?php
namespace MYNAME2;
use MYNAME2 as N;
const MYVAR = 'MYVARNAME';
${N\MYVAR} = 'Y';
echo $MYVARNAME; // PRINT Y
echo ${MYNAME\MYVAR}; /* PRINT Fatal error: Uncaught Error:
Undefined constant 'MYNAME2\MYNAME\MYVAR' */
?>
You can bound a variable to the namespace by wrapping the variable inside a function.
<?php
namespace furniture;
// instead of declaring a $version global variable, wrap it inside a function
function version(){
return "1.3.4";
}
?>
It can be done - sort of.
This is probably extremely bad and should never be done, but it is possible by using variable variables, and the magic constant for namespace.
So a string-variable to name the variable we want to use, like so:
<?php
namespace your\namespace;
$varname = __NAMESPACE__.'\your_variablename'; //__NAMESPACE__ is a magic constant
$namespaced_variable = $$varname; //Note the double dollar, a variable variable
?>
Store Complete classPath in Variable and use after 'new'.
It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string.
<?php
$a = "namespace\\className"; // 'which will print namespace/className'
$obj = new $a;
?>
Alternate ways that can make code more organized:
Instead of like \view\header\$links:
(1) Backslashes in array key for imaginary nesting,
Example:
$myVar['view\header\links'] = 'value';
// OR use multidimentional arrays
$view['header']['links'] = 'value';
(1.1) Use Global Array, Example
// START - SETUP
define('I', 'mySite_19582730');
// END - SETUP
// Usage:
$GLOBALS[I]['view\header\links'] = 'value';
// OR
$GLOBALS[I]['view__header__links'] = 'value';
(1.1.1) Functions to get & set value in Global Array
function set($key, $val){
if (is_string($key)) $GLOBALS['site_8619403725'][$key] = $val;
elseif (is_array($key)){
foreach($key as $ky => &$vl) {
$GLOBALS['mySite_19582730'][$vl] = $val;
}
}
}
function get($key){
return # $GLOBALS['mySite_19582730'][$key];
}
// Usage
set('view\header\search','<div></div>');
set(['view\header\logo','view\header\homeLink'], '');
get('view\header\search');
(2) Use __ (double underscores) in variable name to make imaginary nesting,
Example:
$view__header__links = 'value';
I am trying to assign a variable to a class in PHP, however I am not getting any results?
Can anyone offer any assistance? The code is provided below. I am trying to echo the URL as shown below, by first assigning it to a class variable.
class PageClass {
var $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
$page->get_absolute_path(); //this should echo the URL as defined above - but does not
It also works for me.
Take a look at a live example of your code here.
However, there are a few things you should change about your class.
First, Garvey does make a good point that you should not be using var. That's the older PHP4, less OOP conscious version. Rather declare each variable public or private. In fact, you should declare each function public or private too.
Generally, most classes have private variables, since you usually only want to change the variables in specific ways. To achieve this control you usually set several public methods to allow client functions to interact with your class only in restricted predetermined ways.
If you have a getter, you'd probably want a setter, since these are usually used with private variables, like I described above.
A final note is that functions named get usually return a value. If you want to display a value, it is customary to use a name like display_path or show_path:
<?php
class PageClass
{
private $absolute_path = NULL;
public function set_absolute_path($path)
{
$this->absolute_path = $path;
}
public function display_absolute_path()
{
echo $this->absolute_path;
}
}
$page = new PageClass();
$page->set_absolute_path("http://localhost:8888/smile2/organic/");
$page->display_absolute_path();
// The above outputs: http://localhost:8888/smile2/organic/
// Your variable is now safe from meddling.
// This:
// echo $this->absolute_path;
// Will not work. It will create an error like:
// Fatal error: Cannot access private property PageClass::$absolute_path on ...
?>
Live Example Here
There's a section on classes and objects in the online PHP reference.
class PageClass {
public $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
return $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo $page->get_absolute_path();
Works fine for me.
Have you checked that the script and esp. the code in question is executed at all?
E.g. add some unconditional debug-output to the script. Or install a debugger like XDebug to step through the code and inspect variables.
<?php
class PageClass {
var $absolute_path = NULL; // old php4 declaration, see http://docs.php.net/oop5
function get_absolute_path() { // again old php4 declaration
$url = $this->absolute_path;
echo "debug: "; var_dump($url);
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
echo "debug: page->get_absolute_path\n";
$page->get_absolute_path();