nutballs

This is my

learn

 ing 

PHP

  thread, so I dont start a bunch of threads.

First question or actually confirmation.

Includes are only included once they are encountered in the script correct?

So in otherwords, if I wrapped an include in an if statement that never is true, then the include will never actually get loaded right?

example:
if (1==2)
{
require_once("somefile.

php

 ");
}

that will never get included right? I know it will never get executed, but will it never actually get loaded?

The reason I ask is because in

ASP

  includes are executed inline, but are actually loaded into memory as part of the preproccessing step.

So if you have two functions, named the same exact thing, in two different included files, the compiler would throw an error because of the duplicate function declaration. Even if one of the includes are in an If-Else clause allowing only 1 to be executed.

If the are not loaded until actually executed, this could be benificial to me.

perkiset

quote author=nutballs link=topic=501.msg3235#msg3235 date=1189643765

Includes are only included once they are encountered in the script correct?

True.

quote author=nutballs link=topic=501.msg3235#msg3235 date=1189643765

[clipped, re.

ASP

 ]
So if you have two functions, named the same exact thing, in two different included files, the compiler would throw an error because of the duplicate function declaration. Even if one of the includes are in an If-Else clause allowing only 1 to be executed.

PHP

  will not include another file until it is encountered in the standard program flow. If it is not encountered, it will not be included at all - not even the name space. So you could have a dozen different instances of the same function included based on a switch statement, for example.

However, I am curious about what you want to do here... because there may be other, more effective and efficient ways to do what you're looking for.

nutballs

mostly i just am looking to do conditional config file inclusion, instead of doing it at the actual level of the code. Same constant declarations, but different values in each file.
example would be to mode switch from a DEV instance to LIVE, depending on the domainname.

perkiset

Totally valid and handy.

include '/www/sites/aclient/' . ($mode=='dev') ? 'dev' : 'prod' . '/funcLib.

php

 ';

or

switch($mode)
{
case 'dev':
require_once('dev/funcList.

php

 ');
break;
case 'stage':
require_once('stage/funcList.

php

 ');
break;
case 'production':
require_once('prod/funcList.

php

 ');
break;
}
$var = aFunctionFoundInAll3();

/p

m0nkeymafia

quote author=perkiset link=topic=501.msg3240#msg3240 date=1189661114

Totally valid and handy.

include '/www/sites/aclient/' . ($mode=='dev') ? 'dev' : 'prod' . '/funcLib.

php

 ';

or

switch($mode)
{
case 'dev':
require_once('dev/funcList.

php

 ');
break;
case 'stage':
require_once('stage/funcList.

php

 ');
break;
case 'production':
require_once('prod/funcList.

php

 ');
break;
}
$var = aFunctionFoundInAll3();

/p


that is cool
shame i dont actually go through development and release stages lol

perkiset

Looking this morning I forgot the most completely obvious one,

include "/www/sites/aclient/$mode/funcList.

php

 ";

/p

nutballs

OK next question... Regarding Classes

using a snippet of perks database class from here:
http://www.perkiset.org/forum/

php

 /perks_dbconnection_class-t129.0.html

can the class itself have parameters that are passed upon instantiating? so dbConnection(param1) for example?
is the double underscore in the var declarations anything special? or just a convention on perks part.
The "$doConnect=true" parameter in the dbconnect function. Is that a default for in case that parameter is not passed?
$this refers to the function or the class? im guessing class.
function &cloneConnection() errrr whats the & for?

is there no concept of public and private methods in

php

  classes?
are there no properties in

php

  classes? are the class level vars basically like properties in other languages?



class dbConnection
{
var $__connected;
var $__host;
var $__user;
var $__password;
var $__database;
var $__myConnection;
var $__lastQuery;
var $dataSet;
var $row;

function dbConnection($host, $user, $password, $database, $doConnect=true)
{
$this->__host = $host;
$this->__user = $user;
$this->__password = $password;
$this->__database = $database;
$this->__connected = false;
}
function &cloneConnection()
{
if (!$this->__connected) { $this->connect(); }
return new dbConnection($this->__host, $this->__user, $this->__password, $this->__database);
}

nutballs

So is there any issue with context switching over and over again in a page?

ASP

  could generally care less.

example:

<?

php

  function content() { //START CONTENT HTML============================================= ?>

<form method="POST" action="<?

php

  echo $_SERVER['

PHP

 _SELF']; ?>">
Email: <input type="text" name="email" /><br/>
Password: <input type="password" name="pass" /><br/>
<input type="checkbox" name="remember" value="yes" /> Remember Me<br/>
<input type="submit" value="Login" />
</form>

<?

php

  } //END CONTENT HTML================================================================== ?>


I know this just made perk shiver... But it works really well for my "keep code outta the designers hands" template framework.
In

asp

  you do a large chunk of HTML and just drop in <%=somefunctionthatreturnstext%> wherever you need it.

perkiset

quote author=nutballs link=topic=501.msg3272#msg3272 date=1189814058

can the class itself have parameters that are passed upon instantiating? so dbConnection(param1) for example?

Yes. You can redefine the param list for any constructor in a hierarichy. If you do, you are responsible, of course, for correctly calling your parent.

quote author=nutballs link=topic=501.msg3272#msg3272 date=1189814058

is the double underscore in the var declarations anything special? or just a convention on perks part.
The "$doConnect=true" parameter in the dbconnect function. Is that a default for in case that parameter is not passed?

There are a bunch of magic functions... __construct __destruct, __get __set, __isset, __unset, __call, __autoload, __sleep, __wakeup and __clone. I'll leave it to you to figger out which does what... but in this case, the __ is

PHP

 's convention. I have, however, taken to personally use this same convention for things that I want to remember as "magic."

quote author=nutballs link=topic=501.msg3272#msg3272 date=1189814058

$this refers to the function or the class? im guessing class.

Zactly - the self-instance reference

quote author=nutballs link=topic=501.msg3272#msg3272 date=1189814058

function &cloneConnection() errrr whats the & for?

return a reference rather than a value... in that case, I am returning a reference to an object that is created in that function.

quote author=nutballs link=topic=501.msg3272#msg3272 date=1189814058

is there no concept of public and private methods in

php

  classes?

Not in

PHP

 4, but in

PHP

 5 there is private, protected and public. There are still a few providers out there that use 4.3.4 (the earliest version that is really still viable) but anyone worth there salt has been into 5 for a couple years.

quote author=nutballs link=topic=501.msg3272#msg3272 date=1189814058

are there no properties in

php

  classes? are the class level vars basically like properties in other languages?

Properties in a

PHP

  class are simply variable references. To have an exposed property you'd do this:


class myclass
{
private $var1;
protected $var2;
public $var3;
}


... in that instance, you can talk to $var 3 but not 1 or 2. IMPORTANT: I could easily do this:


$anObj->aVariableThatWasNeverDefined = true;


this is completely valid. The new variable will be attached to <that> instance of the class and you can use it in a read/write way. I think this sucks. This means that you can misspell a var while assigning it to an object and never know that THAT's the reason things don't work later.

The way to get around this is to use the __get and __set magic funcs - with these you can trap all of the getting and setting of vars against $this. Using this functionality, you can replicate normal class events and "do stuff" on the setting of a variable, or prevent the getting of one... or ... well, you know.

perkiset

NBs - we've been talking a lot about strings lately, I forgot one handy little item that many people forget:

PHP

  strings can be read (NOT WRITTEN) in a c-style ie., you can simply ask for the index position of the string rather than substring-ing something out :

$buff = 'ABCdefg';
$heavy = substr($buff, 2, 1);
$light = $buff[2];

$light and $heavy will have the same value, 'C'. Note that strings are zero indexed. Of course if you want a bizarre combo of strings then substr is better... or if you want a long segment of a string then substring is better... but if you want just the first char for example this is *way* faster. This array notation can be used in string dereferences as well, so you could do something like this:

$buff = 'abcdefg';
echo "The second char in '$buff' is {$buff[1]} and the fourth one is {$buff[3]}.";

Note also how you must enclose complex variable names (arrays, object references) in a dereferencing string within curly braces.

/p

nutballs

So a string is stored as an actual array? interesting.

Is substr faster than doing a for loop to get 3 characters from the string for example?

for ( $i= 2; $i== 4; $i+= 1)
{
  echo $buff[$i];
}

perkiset

quote author=nutballs link=topic=501.msg3277#msg3277 date=1189884265

So a string is stored as an actual array? interesting.

That's C for you - I love that about C[++/#/whatever] - strings are literally just arrays of bytes terminated by a chr(0) usually.

PHP

  allows you to read them this way, but not write them. For an example of how to work with C strings and how efficient they are, relook at my IPToNum

PHP

  extension function experiment.

quote author=nutballs link=topic=501.msg3277#msg3277 date=1189884265

Is substr faster than doing a for loop to get 3 characters from the string for example?

for ( $i= 2; $i== 4; $i+= 1)
{
  echo $buff[$i];
}

I'd make the cutoff at about 2 chars... because you're having to move between the PCode and C as the processor runns your script... and the latency added by more code to get the strings (the for loop in your example) would be larger than the overhead of a single call to get a portion of the string. In fact, I'd say that unless you want only 1 or 2 chars I'd use the substr. I thought of this just this morning as I was writing a little processor to handle a particular type of string:
0FirstWord
1Another Phrase
0Some Phrase
3Something Else

... the first char was the "type" of the element and the second half contained names of people. So I parsed it like this:
$type = $inBuff[0];
$name = substr($inBuff, 1, 1024);

... because substr will only go out as far as the string is big. I think this is about the most optimal way to use this trick, although I may be wrong. Sure has been known to happen Applause

IMPORTANT: All this talk about latency is really only a guiding point, because

PHP

  is still fast as shit through a goose. I always think from efficiency first, rather than trying to refactor for speed later. Consider this function which will capitalize a name, regardless of dashes, apostrophes or Mc and

Mac

 :


function cleanup($name)
{
$name = strtolower(trim($name));
$name = join('-', array_map('ucwords', explode('-', $name)));
$name = join(''', array_map('ucwords', explode(''', $name)));
$name = join('

Mac

 ', array_map('ucwords', explode('

Mac

 ', $name)));
$name = join('Mc', array_map('ucwords', explode('Mc', $name)));
return $name;
}


You'd think, if you had a thousand rows in a DB and you used this function against them all that the latency would just be intolerable... but it's not. Once the code is compiled it is really durn fast.

/p

nutballs

is this correct for inserting a date into a Date column in mysql (not date/time or timestamp, just DATE)? This seems hokey to me since in

ASP

  there is a DateAdd function, but I cant find similar for

PHP

 .

$timeframe=100;
$nextdate=date('Y-m-d',mktime(0, 0, 0, date("m"Applause  , date("d"Applause+$timeframe, date("Y"Applause));

perkiset

The correct format for MySQL would be:

$dateStr = date('Y-m-d H:i:s', time());

time() is a seconds since (the Unix epoch, I believe, but WGAF) - so calculating <now> exactly 100 days ago would be:

$aDay = 60*60*24; // 60 secs * 60 mins * 24 hours
$dateStr = date('Y-m-d H:i:s', time() - ($aDay * 100));

For use in a string, you could do something clever like this:


class nutballsDate
{
function MySQL() { return date('Y-m-d H:i:s', time()); }
function Proper() { return date('l FjS, Y', time()); }
}

$nbd = new nutballsDate();
$sql = <<<SQL
select *
from mytable, yourtable, thattable, thistable
where
adatefield <= '{$nbd->MySQL()}' and
someotherfield=anothervalue
order by lastname
SQL;



just so you don't need to test to see, the output would be:
MySQL() -> 2007-09-19 16:20:01
Proper() -> Wednesday September 19th, 2007

/p

perkiset

Further tickle:


class nutballsDate
{
protected $myDate;

__construct($theDate='')
{
if (!$theDate) {$theDate = time(); }
$this->myDate = $theDate;
}

function MySQL() { return date('Y-m-d H:i:s', $this->myDate); }
function Proper() { return date('l FjS, Y', $this->myDate); }
}

// Note that *of course* you'd use constants and other things here,
// but to avoid "magic numbers" I'm doing it mathy for thie example...

$nbd = new nutballsDate(time() + (60 * 60 * 24 * 100)); // 100 days in the future
$sql = "insert into mytable(datefield) values({$nbd->MySQL()})";



/p

perkiset

Are you aware that you can get to MSSQL with

PHP

  as well? It works nicely... it was a little kludgy at first getting my

Linux

  boxes to do it, but once I was on it was great. Have a client that I have to do that with and it's nice to have that in the tool box. Might be another way for you to bridge into this language.

Applause
/p

nutballs

ah true, could just subtract the seconds. though I guess my way might be more readable. not sure about that though, lol.

actually I am using the Date datatype in mysql, which is only the date, no time.

you did something though which I am wondering.

WTF is <<<
is it like a text block? so anything between the <<<SQL and ending SQL is assumed to be a string? and i gather that anything wrapped in {} is run as code right? can you point me to a reference so I can read about that thing.


and yea i know that i can connect to mssql. makes no difference to me, since I normally work with both anyway.

perkiset

quote author=nutballs link=topic=501.msg3336#msg3336 date=1190245033

actually I am using the Date datatype in mysql, which is only the date, no time.

Just the date('Y-m-d', time()) then...

quote author=nutballs link=topic=501.msg3336#msg3336 date=1190245033

WTF is <<<
is it like a text block? so anything between the <<<SQL and ending SQL is assumed to be a string?

Zactly. Been using it for a long while now, but never knew what it was called and just saw it and posted about it today actuall - "Heredoc"  - the format is

$var = [OR]
echo <<<ANAMEOFYOURCHOICE
this
is
text...
$simpleVarRef
{$anObj->aProp()}
{$anArr['idx']}
ANAMEOFYOURCHOICE;

Note that the name of the block is immaterial, except that it must be identical and ON THE ROOT OF THE LINE followed immediately by a ; to denote the end of the block. Even a single space in front of it and the

PHP

  parser will not recognize it as the EOB.

quote author=nutballs link=topic=501.msg3336#msg3336 date=1190245033

and i gather that anything wrapped in {} is run as code right? can you point me to a reference so I can read about that thing.

Not really... it was originally for "complex var types" ie., arrays... but since they added the ability to dereference objects in there you can use it for code by putting the code into the member function. I do that a lot for readability.

Search here for "Heredoc" and you'll see a URL into the

PHP

  reference as well.

/p

vsloathe

Damn all you OO gurus.


Perkiset's Place Home   Politics @ Perkiset's